gpt4 book ai didi

c++ - QTimer 不调用超时槽

转载 作者:行者123 更新时间:2023-11-30 01:08:36 29 4
gpt4 key购买 nike

我试图在不同的 QThread 中使用 QTimer,但我无法连接到 QTimertimeout () 插槽。

我做错了什么?

这是我的代码:

extern MainWindow *mainClass;

class myObj : public QObject
{
Q_OBJECT
public:
explicit myObj(QObject *parent = 0);
~myObj();
QThread workerThread;

int percent;
QTimer *percentTimer;

public slots:
void doWork();
void percentUpdate();
void startFunction();

signals:
void start();
void UpdateResult();
};

myObj::myObj(QObject *parent) : QObject(parent)
{
moveToThread(&workerThread);

connect(&workerThread, SIGNAL(finished()), this, SLOT(deleteLater()));
connect(this, SIGNAL(UpdateResult()), mainClass, SLOT(on_UpdateResult()));
connect(&workerThread, SIGNAL(started()), this, SLOT(doWork()));
connect(this, SIGNAL(start()), this, SLOT(startFunction()));

percent++;
percentTimer = new QTimer();
percentTimer->moveToThread(&workerThread);
percentTimer->setInterval(1000);
connect(percentTimer, SIGNAL(timeout()), this,SLOT(percentUpdate()));

}

myObj::~myObj() {
workerThread.quit();
workerThread.wait();
if (percentTimer) percentTimer->deleteLater();
}

void myObj::doWork()
{
emit start();
workerThread.exec();
}

void myObj::startFunction()
{
percentTimer->start();
QThread::sleep(60);
percentTimer->stop();
}

void myObj::percentUpdate()
{
qDebug() << "In Timer" << percent++;
emit UpdateResult();

}

最佳答案

这是因为您试图从与创建它的线程不同的线程启动您的 QTimer。当使用 QTimer 和线程时,在控制它的线程中创建 QTimer 时应该非常小心。

来自 QTimer class documentation :

In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.

在你的情况下 percentTimer = new QTimer(); 是从主线程执行的,(即使你之前使用过 moveToThread ,这仍然是执行它的主线程),而你的 doWorkstart 信号是从 workerThread 发出的。

例如,您可以从 workerThread 调用的 void init() 槽执行您的 new QTimer,而不是在构造函数中,确保 QTimer 由正确的线程创建和拥有。

myObj::myObj(QObject *parent) : QObject(parent), percentTimer(nullptr)
{
moveToThread(&workerThread);

connect(&workerThread, SIGNAL(finished()), this, SLOT(deleteLater()));
connect(this, SIGNAL(UpdateResult()), mainClass, SLOT(on_UpdateResult()));
connect(&workerThread, SIGNAL(started()), this, SLOT(init()));
connect(&workerThread, SIGNAL(started()), this, SLOT(doWork()));
connect(this, SIGNAL(start()), this, SLOT(startFunction()));

percent++;
}

void myObj::init() {
percentTimer = new QTimer();
percentTimer->setInterval(1000);
connect(percentTimer, SIGNAL(timeout()), this, SLOT(percentUpdate()));
}

关于c++ - QTimer 不调用超时槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128773/

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