我注意到,设置QSpinBox允许的最小值和当前值会自动调用valueChanged插槽。有趣的是,设置最大值并不会导致时隙调用。在我的简单GUI程序中,这会导致一些不必要的行为,导致冗余的API调用,有时会影响应用程序的性能。我假设,valueChanged插槽只适用于用户操作(用小箭头按钮更改或从键盘输入)。这是故意的行为吗?下面是我的程序大致的样子:
添加了一个带有QSpinBox的QtDesigner。此对象的属性在MainWindow构造函数中配置如下:
ui->spinBox->setMinimum(100);
ui->spinBox->setMaximum(100000);
ui->spinBox->setValue(apiCall->getValue()); // retrieve the correct setting from external API
使用valueChanged添加了QtDesigner插槽。
void MainWindow::on_spinBox_valueChanged(int arg1)
{
qDebug() << "valueChanged called with arg: " << arg1;
apiCall->setValue(arg1); // Set a given value in external API
}
我从qDebug在程序启动时的输出中看到了什么:
用arg: 100调用valueChanged
使用arg调用的valueChanged :从外部API调用中检索的值
发布于 2021-06-25 21:13:21
正如我所建议的,最好先设置对象,最后连接信号和插槽。
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow)
{
ui->setupUi(this);
//1st set the object up
ui->spinBox->setMinimum(10);
ui->spinBox->setMaximum(20);
ui->spinBox->setValue(15);
//then connect
connect(ui->spinBox, qOverload<int>(&QSpinBox::valueChanged), this, [](int newValue)
{
qDebug() << "NewValue: " << newValue;
});
但是,如果您的代码设计为在连接信号时隙之后动态地更改这些min和max值呢?
在这种情况下,您可以:阻止QSpinbox的信号,例如:
//then connect
connect(ui->spinBox, qOverload<int>(&QSpinBox::valueChanged), this, [](int newValue)
{
qDebug() << "NewValue: " << newValue;
});
ui->spinBox->blockSignals(true);
//1st set the object up
ui->spinBox->setMinimum(10);
ui->spinBox->setMaximum(20);
ui->spinBox->setValue(15);
ui->spinBox->blockSignals(false);
因此,如您所见,在第二种情况下,blockSignal(true)将“关闭”由QObject发出的信号,因此不会触发任何信号。
https://stackoverflow.com/questions/68132395
复制相似问题