QT中通過函數 connect(objs, SIGNAL(sigFun()), objr, SLOT(slotFun())); 或者 connect( obj1 , &Object1::sigFun , obj2 , &Object2::slotFun ) 來連接信號與槽,傳遞數據
有時我們希望在槽函數中獲取發送信號的對象。可以通過函數“QObject::sender()”獲取發出信號的對象。
例如: 在菜單欄中動態創建一系列的QAction,對應最近打開文件 創建對應的QAction
QList<QString> fileList;for (int i=0; i<fileList.size(); i++) { QAction *act = new QAction(fileList[i]); act->setData(fileList[i]); connect(act, SIGNAL(triggled()), this, SLOT(slotFun()));}這種情況,我們只知道出發了槽函數,但是不知道具體是哪一個QAction發出的信號,此時可以通過上面所提到的函數來獲取發送對象
void slotFun(){ QAction act = qobject_cast<QAction*>(sender()); qDebug() << act->Data();}函數sender()的返回對象為QObject*,通過qobject_cast將其轉換為所需的對象。
新聞熱點
疑難解答