gpt4 book ai didi

c++ - 在不同的线程中创建 QApplication

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:21:38 25 4
gpt4 key购买 nike

我试图在不同的线程中创建 QApplication,但发现了 2 个主要问题:
1- 我无法与 GUI 交互
2- 一些警告:
警告:QApplication 不是在 main() 线程中创建的。
QObject::startTimer: timers cannot be started from another thread//调整小部件大小时发生
QObject::killTimer:计时器不能从另一个线程停止

这是完整的代码:(它可能有一些内存泄漏,但出于测试目的它失败了)

// main.cpp

#include <QCoreApplication>
#include "cthread.h"

int main(int argc, char *argv[])
{
CThread *MyThread = new CThread;
MyThread->start();

QCoreApplication a(argc, argv);

return a.exec();
}

//CThread.h

#ifndef CTHREAD_H
#define CTHREAD_H

#include <QThread>
#include "theqtworld.h"

class CThread : public QThread
{
Q_OBJECT
public:
CThread();
void run( void );

private:
TheQtWorld *mWorld;
};

#endif // CTHREAD_H

//CThread.cpp

#include "cthread.h"
#include <iostream>

CThread::CThread():mWorld(NULL)
{
}


void CThread::run()
{
std::cout << "thread started" << std::endl;
if(!mWorld)
mWorld = new TheQtWorld();

mWorld->OpenWorld();//now it will init all Qt Stuff inside

// if(mWorld) delete mWorld;
// emit this->exit();
}

//theqtworld.h

#ifndef THEQTWORLD_H
#define THEQTWORLD_H

#include <QObject>
#include "mainwindow.h"
#include <QApplication>

class TheQtWorld : public QObject
{
Q_OBJECT
public:
explicit TheQtWorld(QObject *parent = 0);
int OpenWorld(void);

signals:

public slots:

};

#endif // THEQTWORLD_H

//theqtworld.cpp

#include "theqtworld.h"

TheQtWorld::TheQtWorld(QObject *parent) :
QObject(parent)
{
}

int TheQtWorld::OpenWorld()
{
static int arg = 0;
static char *b[2];
b[0] = "a";

QApplication *a = new QApplication(arg, b);
a->setParent(this);

MainWindow w;
w.show();

return a->exec();
}

最佳答案

我会在了解如何克服这个问题后回答我自己的问题

首先问题是将 Qt GUI 作为插件集成到另一个应用程序中,因此主要问题是 Qt 事件与任何其他应用程序事件之间的事件循环冲突

我的第一个想法是将两者分开,这样 QApplication 将留在不同的线程中,但这是一个完全错误的方法,这是我注意到的:

1- Qt GUI 必须留在 main() 线程 所以 QApplication 没有其他地方
2- 为避免阻塞 QApplication::exec() ,将 QApplication::processEvents() 嵌入到其他应用程序事件循环中

这是一个工作代码:

//main.cpp

#include <QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
QApplication mApp(argc, argv);
MainWindow w;
w.show();

//just for testing and holding the program so it doesn't end
for(int i = 0; i < 100000000; ++i)
{
mApp.processEvents();
}
return 0;
}

编辑:感谢 pavel-strakhov 的好建议。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com