Qt World Summit: Register Today!

QThread, execute slot without signal

  • I have been researching about QThreads, and have found out that the best way to use thread is to inherit a QObject and then move that to another thread. Signals are important, because with a queued connection, I don't have to worry about locking anything.

    Because I am using Qt5, I would like to take full advantage of speed. I'm aware of using function pointers to connect, and I would rather that than using invokeMethod. Therefore, I created a signal in my QObject that calls the slot.

    @class Output : public QObject


        connect(this, &Output::postMessage, this, &Output::message, Qt::QueuedConnection);
    ~Output() {}

    public slots:

    void message()
        qDebug() << "Happened in thread " << this->thread();


    void postMessage();


    And then add it to the queue by:
    @Output *output = new Output();
    emit ouput->postMessage();@

    Is my approach good? Will it be faster than invokeMethod since it uses function pointers instead of using strings to get the function? Is there a better way?

  • Lifetime Qt Champion


    emitting a signal from another class is wrong. The signals are emitted from the class that declares them.

    The way of using QThreads by either inheritance or using a worker object is always case specific. You have to carefully choose which solution is the best based on what you will do in your thread.

    Proper locking of resources has to be always analyzed. Qt won't protect automagically for you the accesses made to a shared piece of data.

    I would strongly encourage you to read again the documentation about signals and slots and also threading, look extensively in the examples of Qt to see what you can do.

    Hope it helps

  • For examples you can have a look at

Log in to reply