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博客

相关推荐
何以解忧,唯有..18 分钟前
Python 线程编程:从入门到实战
开发语言·python
SomeB1oody1 小时前
【RustyML入门】7.2. 深入模型持久化
开发语言·后端·机器学习·rust·教程
yaoxin5211231 小时前
502. Java 反射 - 编写 MessageInterceptor 类
java·开发语言
wuyk5551 小时前
Python零基础入门第五章:元组Tuple(不可变容器详解、列表与元组区别)
开发语言·python
三8441 小时前
PHP 污点分析绕过实战:CURL、get_meta_tags 与 fpm_get_status 引入非预定义污点源
开发语言·php
2601_965798471 小时前
Build a Fast, High-Ranking Restaurant Website with Rolanda Theme
开发语言·ios·swift
caimouse2 小时前
ReactOS 窗口系统分析(25):标题栏显示与系统按钮 — nonclient.c 标题栏专题
c语言·开发语言
诺伦2 小时前
Rust 错误处理实战:从 unwrap 到优雅 Result 的进阶之路
开发语言·后端·rust
caimouse2 小时前
ReactOS 窗口系统分析(14):计时器/属性/加速键/热键 — timer.c + prop.c + accelerator.c + hotkey.c
c语言·开发语言·reactos