How to access widgets using qt thread?
In my program I have a widget class with text box and qthread pointer. Using qthread pointer i wan开发者_JS百科t to update the textbox continously by text selection without affect the application. But i cant access the text box. Eventhough i access the textbox by passing the parameter to qthread. I can access the text box and do update text selection few time then my application terminates automatically and indcate error
list_thread: ../../src/XlibInt.c:596: _XPrivSyncFunction: Assertion `(dpy->flags & (1L << 3)) != 0' failed.
In Qt you cannot (or should not) call any GUI functions in another thread than the main thread. What you can do is emit a signal in the worker thread and receive it in the main thread.
For example if you after creating the thread just call
connect(thread, SIGNAL(newText(QString)), lineEdit, SLOT(setText(QString)));
By default this will establish a connection of type Qt::AutoConnection
. Whenever you emit the signal in the same thread where the receiver lives, it is equivalent to a simple function call. But when you emit that signal in another thread (like your new thread), it gets queued and is then delivered when the main thread is scheduled again and continues with its event loop and therefore the slot function will always be called in the thread where the receiver lives. But keep sure that you declare the signal with a value parameter (no pointer or reference), so you really get a copy of the QString
and not a pointer/reference to the thread's string (which might already have been overwritten by the thread).
...
signals:
void newText(QString);
...
You can also configure the connection so that the thread waits (blocks) after emiting until the receiver is finished with handling the signal (has returned from the slot function), by using Qt::BlockingQueuedConnection
as connection type. But in your case this should not be neccessary.
For more information look at Qt's excelent documentation.
精彩评论