[問題] 大量同類widget的event function

看板C_and_CPP作者 (喵。罐頭)時間10年前 (2015/09/06 01:34), 10年前編輯推噓2(204)
留言6則, 4人參與, 最新討論串1/2 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Qt 5.5 問題(Question): 這個問題其實不僅限於Qt, 大概有GUI介面的環境都會遇到 只是想請問一下, 有沒有比較好的寫法..? 假設我的MainWindow中有16個PushButton, 我想要讓每一個按鈕按下之後可以對自己的顏色做變化 單一個按鈕的source code應該會類似這樣: void PushButton_1 () { PushButton_1->ChangeColor(xxx); } 土砲方式就是長了16個像這樣的function, 但是這樣不僅難看, 又不好維護 想請教各位前輩有沒有比較好的方式呢? 像是ButtonPtrAry嗎? --     ▄ 吃免費的便當                                ..   哼!          ▄ 還挑食的喵咪      ▲~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.228.226.49 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1441474456.A.6C8.html

09/06 07:51, , 1F
void PushButton(int buttonId); 像這樣子吧
09/06 07:51, 1F
我現在是將主要要做的事情寫在接收button ptr的function 可是每個按鈕的event還是要分開寫吧@@? void PushButton (QPushButton *thisButton) { ... } void PushButton_1_OnClick () { PushButton(ui->PushButton_1); } void PushButton_2_OnClick () { PushButton(ui->PushButton_2); } void PushButton_3_OnClick () { PushButton(ui->PushButton_3); } ... ※ 編輯: rkcity (36.228.224.148), 09/06/2015 13:07:54

09/06 13:09, , 2F
所以還是會有一大堆PushButton的event function...
09/06 13:09, 2F

09/06 13:15, , 3F
試試 QSignalMapper ?
09/06 13:15, 3F

09/06 16:45, , 4F
在 Qt 裡的最佳解就是 QSignalMapper 沒錯
09/06 16:45, 4F

09/06 16:45, , 5F
我回文好了
09/06 16:45, 5F

09/06 17:53, , 6F
感謝指點!
09/06 17:53, 6F
文章代碼(AID): #1LwoUOR8 (C_and_CPP)
文章代碼(AID): #1LwoUOR8 (C_and_CPP)