QApplication在非主线程中

rcv*_*rcv 10 c++ user-interface qt qt4

我需要在一个非主要的线程中执行()一个QApplication(我的GUI必须是可以在运行时动态加载和卸载的插件,因此我无法访问主线程).有没有人知道(相对)无痛的方式来破解Qt限制在主要之外启动QApplication?

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

blu*_*kin 8

您可以在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;
}
Run Code Online (Sandbox Code Playgroud)

//appthread.h

struct InputArgs{
  int argc;
  char **argv;
};
void StartAppThread(InputArgs &);
Run Code Online (Sandbox Code Playgroud)

//appthread.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);
}
Run Code Online (Sandbox Code Playgroud)


Ves*_*niK 4

如果您使用的是 QThread,那么您已经有了正常的 Qt 事件循环,并且可以在 QThread::run() 函数中运行 exec() 。虽然您无法在主线程之外使用 GUI 对象,但您仍然可以通过排队信号/槽连接与它们进行交互。也许您可以尝试存储指向主线程 QThread 对象的指针并调用 QObject::moveToThread() 将 GUI 对象移动到主线程,而不是将 QApplication 移动到另一个线程。

我认为尝试用不同类型的 hack 和 kluges 来对抗工具包并不是一个好主意。