Qt sender()用法详解

        sender()是QObject类的方法,声明如下:

QObject *sender() const;

        Qt助手的解释如下:

        Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. The pointer is valid only during the execution of the slot that calls this function from this object's thread context.

        翻译如下:

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

        我写了一个demo测试,界面上有3个按钮,都绑定同一个槽函数,点击之后弹出各自的按钮名字,界面如下:

       项目名称test_sender,头文件test_sender.h如下:

#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_test_sender.h"

class test_sender : public QMainWindow
{
	Q_OBJECT

public:
	test_sender(QWidget *parent = Q_NULLPTR);

public slots:
	void onFunc();

private:
	Ui::test_senderClass ui;
};

      test_sender.cpp

#include "test_sender.h"
#include <QMessageBox>

test_sender::test_sender(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	connect(ui.btn1, &QPushButton::clicked, this, &test_sender::onFunc);
	connect(ui.btn2, &QPushButton::clicked, this, &test_sender::onFunc);
	connect(ui.btn3, &QPushButton::clicked, this, &test_sender::onFunc);
}

void test_sender::onFunc()
{
	QPushButton *pBtn = (QPushButton*)sender();
	QMessageBox::about(this, "tips", pBtn->text());
}

      在槽函数中返回按钮的对象指针,从而可以操作该按钮,调用它的一些方法,属性等。

     运行结果,点击按钮1

    点击按钮2

    点击按钮3

   sender的用法也可以用在别的控件上,如果项目有需要可以这样使用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

令狐掌门

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值