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

看板C_and_CPP作者 (←這人是超級笨蛋)時間10年前 (2015/09/06 16:56), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《rkcity (喵。罐頭)》之銘言: : 開發平台(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嗎? 在 Qt 裡的正規解就是 QSignalMapper 這個東西可以自動把類似的 signals 集中管理 但就這個例子而言, 如果要改變的顏色都一樣, 只有 button 不一樣 那麼其實可以用 sender() 就好 connect(button1, SIGNAL(clicked()), this, SLOT(changeButtonColor())); connect(button2, SIGNAL(clicked()), this, SLOT(changeButtonColor())); ... void Receiver::changeButtonColor() { auto button = qobject_cast<MyButton *>(sender()); button->changeColor(...); } 參見 http://doc.qt.io/qt-5/qobject.html#sender 其他 GUI framework 基本上也都會有類似的機制, 可以知道 event 究竟是誰送的 只要得到它, 再稍微處理一下, 就可以整合很多類似的 handlers 例如如果每個按鈕要變的顏色不同, 就加一個 mapping QHash<MyButton *, QColor> buttonColors; 把按鈕與顏色的對應關係填進去 然後就可以用類似的技巧 void Receiver::changeButtonColor() { auto button = qobject_cast<MyButton *>(sender()); button->changeColor(buttonColors[button]); } -- 作者 Linux (Windows) 看板 C_and_CPP 標題 [問題] 如何確認是否 free 對記憶體 時間 Fri Nov 2 00:14:03 2012

11/02 00:43,
valgrind, 但 windowns 版的沒試過XD
11/02 00:43

11/02 00:44,
linux 上那真的是不二選擇了
11/02 00:44

11/02 00:45,
我是用 Windows ....>"<
11/02 00:45
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.217.1.170 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1441529787.A.1BB.html
文章代碼(AID): #1Lw_-x6x (C_and_CPP)
文章代碼(AID): #1Lw_-x6x (C_and_CPP)