3

別のスレッドで QApplication を作成しようとしていますが、2 つの主な問題が見つかりました:
1- GUI と対話できません
2- いくつかの警告:
WARNING: QApplication was not created in the main() thread. QObject::startTimer: timers cannot be started from another thread //happens when resizing widget QObject::killTimer: timers cannot be stopped from another thread

ここに完全なコードがあります: (いくつかのメモリリークがあるかもしれませんが、テスト目的では失敗します)

//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();
}
4

1 に答える 1

2

この問題を克服する方法を理解した後、私は自分の質問に答えます

最初の問題は、Qt GUI をプラグインとして別のアプリケーションに統合することでした。そのため、主な問題は、Qt イベントと他のアプリケーション イベントとの間のイベント ループの衝突でした。

私の最初の考えは両方を分離することだったので、QApplication は別のスレッドにとどまりますが、これは完全に間違ったアプローチであり、私が気づいたことは次のとおりです。

1- Qt GUI は main() スレッドに留まる必要がありますso there is no other place for 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に感謝します。

于 2014-08-17T17:50:02.187 に答える