Qt sender()函數(shù)的具體使用
更新時間:2024年01月03日 09:30:40 作者:----云煙----
在處理信號時,Qt提供了一個特殊的函數(shù)sender(),可以返回發(fā)送信號的對象指針,以實現(xiàn)更靈活的代碼邏輯,本文就來介紹一下Qt sender()函數(shù)的具體使用,感興趣的可以了解一下
sender函數(shù)原型:
QObject *sender() const;
如果在由信號激活的插槽中調用該函數(shù),返回指向發(fā)送信號的對象的指針,否則返回0,該指針僅在從該對象的線程上下文調用此函數(shù)的槽執(zhí)行期間有效。
主要代碼如下:
其中運用了QList類直接foreach循環(huán)連接槽函數(shù)或者每個按鈕都連接
QList<QPushButton *> btnColor; //此代碼寫入MainWindow.h文件中 btnColor << ui->btn_1 << ui->btn_2 << ui->btn_3 ; foreach (QPushButton *btn, btnColor) { connect(btn, SIGNAL(clicked(bool)), this, SLOT(changeColor())); } //connect(ui->btn_1, &QPushButton::clicked, this, &changeColor); //connect(ui->btn_2, &QPushButton::clicked, this, &changeColor); //connect(ui->btn_3, &QPushButton::clicked, this, &changeColor); //槽函數(shù) void MainWindow::changeColor() { QPushButton *pBtn = (QPushButton*)sender(); QMessageBox::about(this, "tips", pBtn->text()); int index = btnColor.indexOf(pBtn); qDebug() << "index == " << index ; }
mainWindow.ui
結果:每個按鍵對應著每個按鍵的截圖;index就是按照上面的btnColor依次排序,btn_1的序號為0,btn_2的序號為1,btn_3的序號為2.
到此這篇關于Qt sender()函數(shù)的具體使用的文章就介紹到這了,更多相關Qt sender()內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Linux系統(tǒng)下如何使用C++解析json文件詳解
JSON(JavaScript Object Notation, JS 對象簡譜) 是一種輕量級的數(shù)據(jù)交換格式。下面這篇文章主要給大家介紹了關于Linux系統(tǒng)下如何使用C++解析json文件的相關資料,需要的朋友可以參考下2021-06-06