开发者

In Qt how to connect a singleton instance to a slot?

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.


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

qRegisterMetaType<IMSS_Status>("IMSS_Status");

to register it correctly with the meta type system. Otherwise, queued slot executions won't work, for instance.


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.


Does the Singleton class have the Q_OBJECT macro also? I don't know if it needs it also or not.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜