如何使自定义小部件中的子小部件的信号可连接?

How to make the signals of child widgets inside a custom widget connectable?

本文关键字:小部 信号 可连接 何使 自定义      更新时间:2023-10-16

我想我对一个对我来说似乎很基本的概念有一些主要问题。

我创建了一个自定义小部件,它实际上只是一小块小部件的集合,因此会出现几次。

class CustomWidget : public QWidget {
Q_OBJECT
public:
explicit CustomWidget(QWidget parent=nullptr) : QWidget(parent) {
spinboxA = new QSpinBox;
spinboxB = new QSpinBox;
QHBoxLayout* layout = new QHBoxLayout(this);
layout.addWidget(spinboxA);
layout.addWidget(spinboxB);
this->setLayout(layout);
}
private:
QSpinBox* spinboxA;
QSpinBox* spinboxB;
};

然后,此自定义小部件在 gui 中使用。当然,我希望这个 gui 对旋转盒值的变化做出反应。在我的理解中,我可以

1(为QSpinBox提供吸气器,并在课堂外连接他们的信号。 2("重新路由"他们的信号,如下例所示

@1(通过connect(customwidget->getSpinboxA(),SIGNAL(valueChanged(int)),this,SLOT(doSomething(int)));使用,我猜?

@2(

class CustomWidget : public QWidget {
Q_OBJECT
public:
explicit CustomWidget(QWidget parent=nullptr) : QWidget(parent) {
spinboxA = new QSpinBox;
spinboxB = new QSpinBox;
QHBoxLayout* layout = new QHBoxLayout;
layout.addWidget(spinboxA);
layout.addWidget(spinboxB);
this->setLayout(layout);
connect(spinboxA,SIGNAL(valueChanged(int)),//...
this,SLOT(onSpinboxAValueChanged(int)));
}
private:
QSpinBox* spinboxA;
QSpinBox* spinboxB;
private slots:
void onSpinboxAValueChanged(int x) {emit spinboxAValueChanged(x);}
//...
signals:
void spinboxAValueChanged(int x)
};

在 gui 类中,人们会connect(customwidget,SIGNAL(spinboxAValueChanged(int),this,SLOT(doSomething(int)));

尤其是版本2(似乎非常混乱,而且...我在问自己 - 如何连接到自定义小部件中的小部件信号?

CustomWidget应该是模块化的,也就是说,它应该像一个黑匣子,应该在其中建立输入并获得输出,所以对我来说,第二个解决方案非常接近它,但我看到了可以改进的东西:没有必要创建一个插槽只是为了发出信号,信号可以连接到其他信号, 我还建议使用新的连接语法。

#include <QApplication>
#include <QHBoxLayout>
#include <QSpinBox>
#include <QWidget>
#include <QDebug>
class CustomWidget : public QWidget {
Q_OBJECT
public:
explicit CustomWidget(QWidget *parent =nullptr):
QWidget(parent),
spinboxA(new QSpinBox),
spinboxB(new QSpinBox)
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(spinboxA);
layout->addWidget(spinboxB);
connect(spinboxA, QOverload<int>::of(&QSpinBox::valueChanged), this, &CustomWidget::spinboxAValueChanged);
connect(spinboxB, QOverload<int>::of(&QSpinBox::valueChanged), this, &CustomWidget::spinboxBValueChanged);
// old syntax:
// connect(spinboxA, SIGNAL(valueChanged(int)), this, SIGNAL(spinboxAValueChanged(int)));
// connect(spinboxB, SIGNAL(valueChanged(int)), this, SIGNAL(spinboxBValueChanged(int)));
}
private:
QSpinBox *spinboxA;
QSpinBox *spinboxB;
signals:
void spinboxAValueChanged(int x);
void spinboxBValueChanged(int x);
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CustomWidget w;
QObject::connect(&w, &CustomWidget::spinboxAValueChanged, [](int i){
qDebug()<< "spinboxAValueChanged: "<< i;
});
QObject::connect(&w, &CustomWidget::spinboxBValueChanged, [](int i){
qDebug()<< "spinboxBValueChanged: "<< i;
});
w.show();
return a.exec();
}
#include "main.moc"