我需要在一个非主线程中执行一个 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/