【发布时间】:2021-08-28 06:21:09
【问题描述】:
我正在运行时创建多个 QWidget_WindowContact 类型的对象。当我单击增量或减量按钮时,最后生成的对象中的值会更新,而不是同一对象中的值。
我正在努力正确链接信号和插槽,以便在运行时生成多个相同类型的对象时,按钮发出的信号与正确对象中的信号相对应。
QWidget_WindowContact.h:
#ifndef QWIDGET_WINDOWCONTACT_H
#define QWIDGET_WINDOWCONTACT_H
#include "qwidget.h"
class QWidget_WindowContact : public QWidget
{
Q_OBJECT
public:
explicit QWidget_WindowContact(QWidget* parent = nullptr);
private slots:
void on_btnInc_clicked();
void on_btnDec_clicked();
void on_btnDel_clicked();
private:
QPoint offset;
protected:
};
#endif // QWIDGETTEMP_H
QWidget_WindowContact.h:
#include <QtWidgets>
#include "QWidget_WindowContact.h"
QSpinBox* counter;
QWidget_WindowContact::QWidget_WindowContact(QWidget* parent) : QWidget(parent)
{
this->setObjectName("");
setMinimumSize(100, 100);
this->setStyleSheet("border: 1px solid gray");
QVBoxLayout* layout = new QVBoxLayout(this);
QLabel* name = new QLabel("WINDOWCONTACT", this);
QPushButton* btnInc = new QPushButton("Increment", this);
btnInc->setObjectName("btnInc");
QPushButton* btnDec = new QPushButton("Decrement", this);
btnDec->setObjectName("btnDec");
QPushButton* btnDel = new QPushButton("Delete Widget", this);
btnDel->setObjectName("btnDel");
counter = new QSpinBox(this);
counter->setObjectName("counter");
connect(this->findChild<QPushButton*>("btnInc"), SIGNAL(clicked()), this, SLOT(on_btnInc_clicked()));
connect(this->findChild<QPushButton*>("btnDec"), SIGNAL(clicked()), this, SLOT(on_btnDec_clicked()));
connect(this->findChild<QPushButton*>("btnDel"), SIGNAL(clicked()), this, SLOT(on_btnDel_clicked()));
layout->addWidget(name);
layout->addWidget(counter);
layout->addWidget(btnInc);
layout->addWidget(btnDec);
layout->addWidget(btnDel);
}
void QWidget_WindowContact::on_btnInc_clicked()
{
counter->setValue(counter->value() + 1);
}
void QWidget_WindowContact::on_btnDec_clicked()
{
counter->setValue(counter->value() - 1);
}
void QWidget_WindowContact::on_btnDel_clicked()
{
close();
}
【问题讨论】:
标签: c++ qt signals-slots