Qt sender()函数

sender函数原型:

QObject *sender() const;

 如果在由信号激活的插槽中调用该函数,返回指向发送信号的对象的指针,否则返回0,该指针仅在从该对象的线程上下文调用此函数的槽执行期间有效。

主要代码如下:
其中运用了QList类直接foreach循环连接槽函数或者每个按钮都连接

QList 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);

//槽函数
void MainWindow::changeColor()
{
    QPushButton *pBtn = (QPushButton*)sender();
    QMessageBox::about(this, "tips", pBtn->text());

    int index = btnColor.indexOf(pBtn);

    qDebug() << "index == " << index ;

}

mainWindow.ui

Qt sender()函数_第1张图片

结果:每个按键对应着每个按键的截图;index就是按照上面的btnColor依次排序,btn_1的序号为0,btn_2的序号为1,btn_3的序号为2.

Qt sender()函数_第2张图片Qt sender()函数_第3张图片Qt sender()函数_第4张图片

参考:Qt sender()用法详解-CSDN博客

你可能感兴趣的:(qt,开发语言)