如何使用qt线程访问小部件?
在我的程序中,我有一个带有文本框和 qthread 指针的小部件类。使用 qthread 指针,我想通过文本选择连续更新文本框而不影响应用程序。但我无法访问文本框。尽管我通过将参数传递给 qthread 来访问文本框。我可以访问文本框并更新文本选择几次,然后我的应用程序自动终止并指示错误
list_thread: ../../src/XlibInt.c:596: _XPrivSyncFunction: Assertion `(dpy->flags & ( 1L << 3)) != 0' 失败。
In my program I have a widget class with text box and qthread pointer. Using qthread pointer i want 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Qt 中,您不能(或不应)在主线程以外的其他线程中调用任何 GUI 函数。您可以做的是在工作线程中发出信号并在主线程中接收它。
例如,如果您在创建线程后只需调用
默认情况下,这将建立
Qt::AutoConnection
类型的连接。每当您在接收者所在的同一线程中发出信号时,它就相当于一个简单的函数调用。但是,当您在另一个线程(例如您的新线程)中发出该信号时,它会排队,然后在主线程再次调度并继续其事件循环时传递,因此槽函数将始终在该线程中被调用接收者生活。但请确保使用值参数(无指针或引用)声明信号,这样您实际上会获得 QString 的副本,而不是指向线程字符串的指针/引用(可能已经有已被线程覆盖)。您还可以配置连接,以便线程在发出后等待(阻塞),直到接收者完成处理信号(已从槽函数返回),使用 Qt::BlockingQueuedConnection 作为连接类型。但就您而言,这应该不是必需的。
有关更多信息,请参阅 Qt 的优秀文档。
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
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 theQString
and not a pointer/reference to the thread's string (which might already have been overwritten by the thread).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.