防止在 Qt 中触发信号

2023-07-01C/C++开发问题
9

本文介绍了防止在 Qt 中触发信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我们有一个 QCheckBox 对象,当用户检查它或删除检查时,我们想要调用一个函数,因此我们将我们的函数连接到 stateChanged ( int state ) 信号.另一方面,根据某些情况,我们也在代码中改变了 QCheckBox 对象的状态,这会导致不需要的信号.

We have a QCheckBox object, when user checks it or removes check we want to call a function so we connect our function to stateChanged ( int state ) signal. On the other hand, according to some condition we also change the state of QCheckBox object inside code, and this causes the unwanted signal.

在某些情况下有什么办法可以防止发射信号吗?

Is there any way to prevent firing signal under some conditions?

推荐答案

您可以使用 clicked 信号,因为它仅在用户实际单击复选框时发出,而不是在您使用 setChecked.

You can use the clicked signal because it is only emitted when the user actually clicked the check box, not when you manually check it using setChecked.

如果您只是不想在某个特定时间发出信号,可以使用 QObject::blockSignals 像这样:

If you just don't want the signal to be emitted at one specific time, you can use QObject::blockSignals like this:

bool oldState = checkBox->blockSignals(true);
checkBox->setChecked(true);
checkBox->blockSignals(oldState);

这种方法的缺点是所有信号都将被阻塞.但我想这在 QCheckBox 的情况下并不重要.

The downside of this approach is that all signals will be blocked. But I guess that doesn't really matter in case of a QCheckBox.

这篇关于防止在 Qt 中触发信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6