如何将点击的信号和插槽添加到qt中的自定义按钮中

How to add clicked signal and slot to custom button in qt

本文关键字:添加 按钮 qt 插槽 自定义 信号      更新时间:2023-10-16

我有一个从QPushButton继承的Box类。我想通过使用connect(SIGNAL和SLOT(在按钮上有一个onClick事件,并调用box.h 中声明的自定义函数onClick()

box.h
#ifndef BOX_H
#define BOX_H
#include <QPushButton>
class Box : public QPushButton {
public:
Box(const QString& text, QWidget* parent = nullptr);
void onClick();
};
#endif // BOX_H
//box.cpp
#include "box.h"
Box::Box(const QString& text, QWidget* parent)
: QPushButton(text, parent)
{
connect(this, SIGNAL(clicked()), SLOT(this->onClick()));
}
void Box::onClick()
{
this->setText("Something");
}

您的盒子需要用于定义插槽的标签

class Box : public QPushButton
{
Q_OBJECT
public:
Box(const QString& text, QWidget* parent = nullptr);
//may be public or private
public slots:

void onClick();
};