加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

Qt库事件循环问题

发布时间:2020-12-14 04:27:16 所属栏目:Windows 来源:网络整理
导读:我正在编写一个DLL,它被另一个应用程序用作插件,并希望利用Qt的能力. 我已经设置,编译和运行所有类,但没有发出任何信号. 所以似乎没有QEventLoop. 尝试1: 我将我的主类修改为子类QThread而不是QObject,并在run()中创建一个QEventLoop,连接所有信号/槽,并执
我正在编写一个DLL,它被另一个应用程序用作插件,并希望利用Qt的能力.
我已经设置,编译和运行所有类,但没有发出任何信号.
所以似乎没有QEventLoop.

尝试1:
我将我的主类修改为子类QThread而不是QObject,并在run()中创建一个QEventLoop,连接所有信号/槽,并执行该线程.
但它没有说没有QApplication就没有QEventLoop.

尝试2:
我修改了主类(仍然继承QThraed)而不是实例化QCoreApplication,然后执行应用程序.
警告说QApplication不是在main()线程中创建的,仍然不会发出信号.

我不确定该怎么做.我显然无法在将使用我的插件的应用程序中创建QCoreApplication,并且我无法在没有插件的情况下发出信号.

我已经包含了一个简单的(并且可怕写的)测试应用程序,它应该说明我的问题:

任何帮助,将不胜感激!

main.cpp中:

#include <iostream>
#include "ThreadThing.h"
using namespace std;
int main(int argc,char *argv[])
{
    cout << "Main: " << 1 << endl;
    ThreadThing thing1;
    cout << "Main: " << 2 << endl;
    thing1.testStart();
    cout << "Main: " << 3 << endl;
    thing1.testEnd();
    cout << "Main: " << 4 << endl;
    thing1.wait(-1);
    cout << "Main: " << 5 << endl;
    return 0;
}

ThreadThing.h:

#ifndef THREADTHING_H
#define THREADTHING_H
#include <QThread>
class ThreadThing : public QThread
{
    Q_OBJECT
public:
    ThreadThing();
    virtual void run();
    void testStart();
    void testEnd();
public slots:
    void testSlot();
signals:
    void testSignal();
};
#endif//THREADTHING_H

ThreadThing.cpp:

#include "ThreadThing.h"
#include <iostream>
#include <QCoreApplication>

using namespace std;

ThreadThing::ThreadThing()
{
    cout << "Constructor: " << 1 << endl;
    this->start();
    cout << "Constructor: " << 2 << endl;
}

void ThreadThing::run()
{
    cout << "Run: " << 1 << endl;
    int i = 0;
    cout << "Run: " << 2 << endl;
    QCoreApplication* t = new QCoreApplication(i,0);
    cout << "Run: " << 3 << endl;
    connect(this,SIGNAL(testSignal()),this,SLOT(testSlot()),Qt::QueuedConnection);
    cout << "Run: " << 4 << endl;
    t->exec();
    cout << "Run: " << 5 << endl;
}

void ThreadThing::testStart()
{
    cout << "TestStart: " << 1 << endl;
    emit testSignal();
    cout << "TestStart: " << 2 << endl;
}

void ThreadThing::testEnd()
{
    cout << "TestEnd: " << 1 << endl;
    this->quit();
    cout << "TestEnd: " << 1 << endl;
}

void ThreadThing::testSlot()
{
    cout << "TEST WORKED" << endl;
}

输出:

Main: 1
Constructor: 1
Constructor: 2
Main: 2
TestStart: 1
TestStart: 2
Main: 3
TestEnd: 1
TestEnd: 1
Main: 4
Run: 1
Run: 2
WARNING: QApplication was not created in the main() thread.
Run: 3
Run: 4

解决方法

您必须创建QCoreApplication或QApplication,您必须在主线程中执行此操作.

这并不意味着你不能在你的插件中添加代码…除非应用程序总是在自己的线程中运行每个插件.

如果应用程序正在执行该操作,那么您可以尝试连接到应用程序使用的任何本机事件循环,并安排它在主线程中调用插件中的某些函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读