[英]C++ QThread and connect causing crashes
My QThread counter crashes giving odd results for what the number should be as the Thread counts properly but in the SetLabel function I get a different number to whats in the QThread ands it then crashes after 3 seconds and the label doesnt seem to update. 我的QThread计数器崩溃,当线程正确计数时,给出的数字应该是奇怪的结果,但是在SetLabel函数中,我得到的数字不同于QThread中的数字,然后3秒钟后崩溃,标签似乎没有更新。
QThread* CountThread = new QThread;
Counter* Count = new Counter();
Count->moveToThread(CountThread);
connect(CountThread, SIGNAL(started()), Count, SLOT(Process()));
connect(Count, &Counter::SecondsUpdate, this, [=]{ SetLabel(Count->Seconds) ;});
connect(Count, SIGNAL(finished()), CountThread, SLOT(quit()));
CountThread->start();
void Counter::Process()
{
int secs = 0;
while (secs < 1000)
{
qDebug() << "hello" << secs;
secs += 1;
Sleep(1000);
emit SecondsUpdate();
}
emit finished();
}
void BaseWindow::SetLabel(int Seconds)
{
qDebug() << Seconds;
this->Test->setText(QString("Seconds: " + QString::number(Seconds)));
}
class Counter : public QObject
{
Q_OBJECT
public slots:
void Process();
signals:
void finished();
void SecondsUpdate();
public:
int getValue() { return Seconds;}
int Seconds;
};
EDIT: The issue seems to lie in the changing of the label as I commented this->Text->setText out and it didnt crash 编辑:问题似乎在于更改标签,因为我将this-> Text-> setText注释掉,并且它没有崩溃
The code shown has two basic problems. 显示的代码有两个基本问题。
Counter::Seconds
is never initialized/updated. Counter::Seconds
永远不会初始化/更新。 Count
to a new QThread
you continue to access it from the main thread. Count
移到新的QThread
您可以继续从主线程访问它。 You could solve both of these by getting rid of the Seconds
member and just passing the local counter secs
as a parameter to the Counter::SecondsUpdate
signal... 您可以通过摆脱
Seconds
成员,而只是将本地计数器secs
作为参数传递给Counter::SecondsUpdate
信号来解决这两个问题。
class Counter: public QObject
{
Q_OBJECT;
public slots:
void Process();
signals:
void finished();
void SecondsUpdate(int seconds);
public:
};
void Counter::Process ()
{
int secs = 0;
while (secs < 1000)
{
qDebug() << "hello" << secs;
secs += 1;
/*
* Sleep(1000) --> QThread::sleep(1)
*/
QThread::sleep(1);
/*
* Pass secs as a parameter to the SecondsUpdate signal.
*/
emit SecondsUpdate(secs);
}
emit finished();
}
Then, change the relevant connect
call from... 然后,从...更改相关的
connect
呼叫。
connect(Count, &Counter::SecondsUpdate, this, [=]{ SetLabel(Count->Seconds) ;});
to... 至...
connect(Count, &Counter::SecondsUpdate, this, &BaseWindow::SetLabel);
通过将标签作为指针并在函数中对其进行编辑来修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.