c++ - 非主线程中的QApplication

标签 c++ user-interface qt qt4

我需要在一个非主线程中执行一个 QApplication(我的 GUI 必须是可以在运行时动态加载和卸载的插件,所以我无法访问主线程)。有谁知道一种(相对)轻松的方法来绕过 Qt 对在 main 之外启动 QApplication 的限制?

我正在 Linux 中使用 gcc4.3.4 在 C++ 中使用 Qt4 进行开发。

最佳答案

您可以在 PThread 中启动一个 QApplication,如下所示

// main.cpp

#include <iostream>
#include "appthread.h"
int main(int argc, char *argv[]) {
  InputArgs args = {argc, argv};
  StartAppThread(args);
  sleep(10);
  return 0;
}

//应用线程.h

struct InputArgs{
  int argc;
  char **argv;
};
void StartAppThread(InputArgs &);

//应用线程.cpp

#include <QApplication>
#include <QMainWindow>
#include <QPushButton>
#include "appthread.h"
#include <pthread.h>

void *StartQAppThread(void *threadArg) {
  InputArgs *args = (struct InputArgs*) threadArg;
  QApplication app(args->argc, args->argv);
  QMainWindow w;
  w.show();
  w.setCentralWidget(new QPushButton("NewButton"));
  app.exec();
  pthread_exit(NULL);
}

void StartAppThread(InputArgs &args) {
  pthread_t thread1;  
  int rc = pthread_create(&thread1, NULL, StartQAppThread, (void*)&args);
}

关于c++ - 非主线程中的QApplication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2798832/

相关文章:

c++ - 在 GCC 中为类使用属性打包

c++ - 调整通过引用传递的动态分配数组的大小

QT : QListwidget signals when using uo and down arrows

qt - 使用 QObject 代替容器

c++ - 从 Mac 为 WIndows、Linux 交叉编译 C++/QT

C++ 项目类型 : unicode vs multi-byte; pros and cons

c++ - 编译器不生成 move 构造函数

user-interface - 你最喜欢的用户界面是什么? (Web应用程序)

python - Tkinter 网格布局不会扩展

c++ - Windows 32 API : 2 Checkboxes acting as one?