同一个cpp文件内如何实现两个按钮的槽函数互通
在同一个.cpp文件中,可以通过以下两种方式实现两个按钮的槽函数互通。
- 使用成员变量: 在类的定义中声明两个按钮对象的成员变量,并在构造函数中连接按钮的clicked()信号到对应的槽函数。在槽函数中可以通过判断sender()来确定是哪个按钮触发了该槽函数。
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
private slots:
void onButton1Clicked();
void onButton2Clicked();
private:
QPushButton *button1;
QPushButton *button2;
};
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
button1 = new QPushButton("Button 1", this);
button2 = new QPushButton("Button 2", this);
connect(button1, &QPushButton::clicked, this, &Widget::onButton1Clicked);
connect(button2, &QPushButton::clicked, this, &Widget::onButton2Clicked);
}
void Widget::onButton1Clicked()
{
if (sender() == button1)
{
// Button 1 clicked
}
else if (sender() == button2)
{
// Button 2 clicked
}
}
void Widget::onButton2Clicked()
{
if (sender() == button1)
{
// Button 1 clicked
}
else if (sender() == button2)
{
// Button 2 clicked
}
}
- 使用Lambda表达式: 在构造函数中连接按钮的clicked()信号到Lambda表达式,通过Lambda表达式中的参数来判断是哪个按钮触发了该槽函数。
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
};
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QPushButton *button1 = new QPushButton("Button 1", this);
QPushButton *button2 = new QPushButton("Button 2", this);
connect(button1, &QPushButton::clicked, [this](bool checked) {
if (sender() == button1)
{
// Button 1 clicked
}
else if (sender() == button2)
{
// Button 2 clicked
}
});
connect(button2, &QPushButton::clicked, [this](bool checked) {
if (sender() == button1)
{
// Button 1 clicked
}
else if (sender() == button2)
{
// Button 2 clicked
}
});
}
无论使用哪种方式,都可以实现两个按钮的槽函数互通
原文地址: http://www.cveoy.top/t/topic/iJY2 著作权归作者所有。请勿转载和采集!