QLabel update from thread



  • Hi all, I'm new to QT, I have searched a lot on internet for a solution but nothing.
    I have a QLabel and I want to update it from inside another thread.
    If I use

    ui->label1->setText("Hello Qt!");

    all is working fine, but if I want to change text color

    ui->label1->setText("<h2><i>Hello</i><font color=red>Qt!</font></h2>");

    I have a cross threading exception and I have to close the application.
    The two examples woks fine outside a thread.
    I use Visual C++ 2008, not managed code, the target device is Windows CE;

    Tank you



  • You cannot manipulate a widget from a secondary thread.

    Have your surrounding class a setText() slot which is called from the secondary thread, and forward the text to the setText() slot of the label.



  • Hi,
    you can't access gui elements from other threads. Simplest way to solve your problem is to use signals and slots. In your not main thread emit signal which will trigger slot in your main thread and update necessary gui elements.

    edit: Awww, late again... :(



  • Or use "QMetaObject::invokeMethod":http://qt-project.org/doc/qt-4.8/qmetaobject.html#invokeMethod with Qt::QueuedConnection

    @
    QMetaObject::invokeMethod(ui->label1, "setText" Qt::QueuedConnection Q_ARG(QString, <stringToSend>));
    @



  • Perfect, now is working

    Thank you

    [quote author="Tomma" date="1344511439"]Or use "QMetaObject::invokeMethod":http://qt-project.org/doc/qt-4.8/qmetaobject.html#invokeMethod with Qt::QueuedConnection

    @
    QMetaObject::invokeMethod(ui->label1, "setText" Qt::QueuedConnection Q_ARG(QString, <stringToSend>));
    @[/quote]


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.