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的用法也可以用在别的控件上,如果项目有需要可以这样使用。

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐