您当前的位置: 首页 >  qt

令狐掌门

暂无认证

  • 2浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Qt sender()用法详解

令狐掌门 发布时间:2020-02-29 14:10:14 ,浏览量:2

        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 
#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 

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

关注
打赏
1652240117
查看更多评论
立即登录/注册

微信扫码登录

0.0520s