在 Qt 中如何将单例实例连接到插槽?
我在 Qt Creator 中编程并遇到了问题。我创建了一个单例类,我试图将它连接到小部件中的一个插槽,但它不接受返回的指针 来自 Singleton::getInstance()
作为发出信号的同一实例。
我的代码如下:
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void setString(int var);
}
实现:
connect(Singleton::getInstance(),SIGNAL(changeString(int)),this,SLOT(setString(int)));
单例类中的信号:
signals:
void changeString(int var);
单例类中对信号的调用:
emit(Singleton::getInstance()->changeString(5));
信号发出时没有任何反应。调试器不进入插槽。
I'm programming in Qt Creator and encountered a problem. I made a singleton class, and I'm trying to connect it to a slot in the widget, but it doesn't take the pointer that returns
from Singleton::getInstance()
as the same instance that emits the signal.
My code is as follows:
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void setString(int var);
}
Implementation:
connect(Singleton::getInstance(),SIGNAL(changeString(int)),this,SLOT(setString(int)));
Signal in the singleton class:
signals:
void changeString(int var);
the call to the signal in the singleton class:
emit(Singleton::getInstance()->changeString(5));
Nothing happens when signal emits. The debugger doesn't enter the slot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最有可能的是插槽的方法签名不同 -
setString(IMSS_Status);
与setString(int);
另外,如果是自定义类型,您应该调用
使用元类型系统正确注册它。否则,例如,排队的槽执行将无法工作。
Most probably it's the differing method signature of the slot -
setString(IMSS_Status);
vs.setString(int);
Also, in case of a custom type, you should call
to register it correctly with the meta type system. Otherwise, queued slot executions won't work, for instance.
您的问题可能是由方法签名引起的。在与插槽建立连接信号之前,您应该使用
qRegisterMetaType("Class Definition name"); 定义到系统的信号,
并且是changeString签名的信号吗? “void changeString(int)”
我遇到了你的问题,我通过制作 qRegisterMetaType 和控制签名解决了我的问题。
Your problem may be caused by signature of the methods. Before you make connect signal with slot u should define your signal to system by using
qRegisterMetaType<Your Class >("Class Definition name");
And is the signal of changeString signature ? "void changeString(int)"
i had encountered your problem and i solved my problem by making qRegisterMetaType and controlling signatures.
Singleton 类也有 Q_OBJECT 宏吗?我不知道它是否也需要它。
Does the Singleton class have the
Q_OBJECT
macro also? I don't know if it needs it also or not.我倾向于
emit(Singleton::getInstance()->changeString(5));
不正确。emit 应该从
Singleton
函数内部调用,如下所示:emit(changeString(5));
我很惊讶您发布的代码在没有警告的情况下编译和运行,我会预计会出现有关信号不存在的运行时错误。
I would lean towards
emit(Singleton::getInstance()->changeString(5));
not being correct.emit should be called from inside a
Singleton
function as follows:emit(changeString(5));
I'm surprised the code you posted compiles and runs without warning, I would have expected a runtime error about the signal not existing.