How do I create a Window in different QT threads?(如何在不同的 QT 线程中创建窗口?)
问题描述
我有一个应用程序,其中每个线程(主线程除外)都需要创建自己的窗口.我尝试创建一个线程,然后在 run 函数中调用 this->exec() .但是,我什至在调用之前收到一个错误:ASSERT 在 QWidget 中失败:Widgets must be created in the GUI thread."
I have an application in which each thread (except the main thread) needs to create its own window. I tried creating a thread and then calling this->exec() in the run function. However, I get an error before I even get to that call: ASSERT failure in QWidget: "Widgets must be created in the GUI thread."
我想弹出一个消息窗口.问题是源有多个线程,每个线程可能需要弹出自己的消息.
I want to popup a message window. The problem is that the source has multiple threads each of which may need to popup its own message.
推荐答案
如果你需要在不同的(非主)线程中创建 QWidget(或其他一些 gui 组件),你可以在这样的线程中实现它方式:
If you need to create QWidget(or some other gui component(s)) in different(non-main) thread(s) you can implement it in such way:
- 创建包含 gui 组件的简单包装器: 
- Create simple wrapper which holds gui component: 
// gui component holder which will be moved to main thread
class gui_launcher : public QObject
{
  QWidget *w;
  // other components
  //..
public:
  virtual bool event( QEvent *ev )
  {   
    if( ev->type() == QEvent::User )
    {
      w = new QWidget;
      w->show();
      return true;
    }
    return false;
  }
};
在主线程中创建QApplication对象
create QApplication object in main thread
另一个线程主体:
..
  // create holder
  gui_launcher gl;
  // move it to main thread
  gl.moveToThread( QApplication::instance()->thread() );
  // send it event which will be posted from main thread
  QCoreApplication::postEvent( &gl, new QEvent( QEvent::User ) );
..
开心点,:)
be happy, :)
这篇关于如何在不同的 QT 线程中创建窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不同的 QT 线程中创建窗口?
 
				
         
 
            
        基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				