Qt sender()函数

sender函数原型:

复制代码
QObject *sender() const;

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

主要代码如下:

其中运用了QList类直接foreach循环连接槽函数或者每个按钮都连接

复制代码
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);

//槽函数
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()用法详解-CSDN博客

相关推荐
AI玫瑰助手7 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车7 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋8 小时前
C++14特性
开发语言·c++·c++14特性
读书札记20228 小时前
Qt界面卡死问题探讨及解决方法
qt
JAVA社区9 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子9 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php
z落落9 小时前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#
学代码的真由酱10 小时前
Java多用户一对一网页聊天室-测试报告
java·开发语言·功能测试·测试
人道领域10 小时前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法
xiaoshuaishuai810 小时前
C# AvaloniaUI动态显示图片
开发语言·c#