我正在尝试在我的 UI 中插入一个复选框,该复选框可以根据其选中状态将来自另一个类的 bool 变量设置为 true 或 false。问题是没有发出信号。
该变量在我的第一个类 (renderarea.h) 的头文件中定义为
public: bool selectionMode;
插槽在第 2 类的头文件中定义为 void
protected slots: void setSelectionMode(bool mode);
并且信号连接到构造函数中我的第二类源文件中的插槽,如下所示:
PaintWidget::PaintWidget(QWidget *parent) : QWidget(parent), ui(new Ui::PaintWidget) { connect(ui->selectionModeCheckBox, SIGNAL(toggled(bool)), this, SLOT(setSelectionMode(bool))); } void PaintWidget::setSelectionMode(bool mode) { ui->displayWidget->selectionMode = mode; QMessageBox msgbox; if (ui->displayWidget->selectionMode == true) msgbox.setText("selection mode is true"); else msgbox.setText("selection mode is false"); }
我在这里使用 QMessageBox 只是为了测试。但是在调试时我看到信号没有发出。我做错了什么?
最佳答案
您需要确保许多事情都到位:
setupUi
连接
成功- 复选框值真的改变了
首先,我没有看到您在哪里调用了 setupUi
。您需要在构造函数中执行此操作:
PaintWidget::PaintWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::PaintWidget)
{
ui->setupUi(this);
connect(ui->selectionModeCheckBox,
SIGNAL(toggled(bool)), this, SLOT(setSelectionMode(bool)));
}
其次,确保connect的返回值表示成功。
第三,我假设您是手动单击复选框,但为了测试,您可以在构造函数中连接后执行此操作:
ui->selectionModeCheckBox->setChecked(true);
关于c++ - 为什么 QCheckBox 的信号没有发出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6360495/