项目场景:
经常会碰到一些场景,数据处理时需要短暂的断开信号和槽的连接,但是处理完又需要保持连接,用于更新状态。
解决办法:
方法一:
需要断开的地方diconnect,需要连接的地方connect,最简单直接的办法,但是会很繁琐,如果频繁操作,多出了非常多的重复代码,逻辑混乱。
disconnect(&sender, SIGNAL(someSignal()), this, SLOT(someSlot()));
connect(&sender, SIGNAL(someSignal()), this, SLOT(someSlot()));
方法二:
使用标志位,通过条件判断的方式控制功能的开关。但是这么做有点底层状态机的模子,看起来也复杂。
#include <QObject>
class MyClass : public QObject {
Q_OBJECT
public:
MyClass() : isEnabled(true) {
connect(&sender, SIGNAL(someSignal()), this, SLOT(someSlot()));
}
void temporarilyDisable() {
isEnabled = false;
}
void enable() {
isEnabled = true;
}
private slots:
void someSlot() {
if (isEnabled) {
// slot
// true handle
}
}
private:
QObject sender;
bool isEnabled;
};
方法三:
使用官方QSignalBlocker,这个是这种场景下最推荐的,用于阻塞对象的所有信号,而且是作用域生效,超出作用域后自动解除。
#include <QObject>
#include <QSignalBlocker>
class MyClass : public QObject {
Q_OBJECT
public:
MyClass() {
connect(&sender, SIGNAL(someSignal()), this, SLOT(someSlot()));
}
void performOperationWithSignalsBlocked() {
{
QSignalBlocker blocker(sender);
// Perform operations while signals are blocked
}
// Signals are unblocked here
}
private slots:
void someSlot() {
// slot implementation
}
private:
QObject sender;
};
4587

被折叠的 条评论
为什么被折叠?



