C++ C++;QThread和connect导致崩溃
当线程正确计数时,我的QThread计数器崩溃,给出了该数字的奇数结果,但在SetLabel函数中,我得到了与QThread中的数字不同的数字,然后在3秒后崩溃,标签似乎没有更新C++ C++;QThread和connect导致崩溃,c++,multithreading,qt,user-interface,qt5,C++,Multithreading,Qt,User Interface,Qt5,当线程正确计数时,我的QThread计数器崩溃,给出了该数字的奇数结果,但在SetLabel函数中,我得到了与QThread中的数字不同的数字,然后在3秒后崩溃,标签似乎没有更新 QThread* CountThread = new QThread; Counter* Count = new Counter(); Count->moveToThread(CountThread); connect(CountThread, SIGNAL(started()), Count, SLOT(Pro
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;
};
QThread*CountThread=新的QThread;
计数器*计数=新计数器();
计数->移动到线程(计数线程);
连接(CountThread、信号(start())、计数、插槽(Process());
连接(计数,&计数器::SecondsUpdate,this,[=]{SetLabel(计数->秒);});
连接(计数、信号(finished())、计数线程、插槽(quit());
CountThread->start();
无效计数器::进程()
{
整数秒=0;
而(秒<1000)
{
qDebug()Text->setText out,它没有崩溃通过将标签作为指针传递并在函数中编辑它来修复。显示的代码有两个基本问题
计数器::秒
从未初始化/更新
将Count
移动到新的QThread
后,您将继续从主线程访问它
您可以通过去掉Seconds
成员并将本地计数器secs
作为参数传递给计数器::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();
}
到
@eyllanesc只是windows.h中的一个睡眠函数,它是Count->Seconds
?@eyllanesc类计数器:public QObject{Q_对象public slots:void进程();信号:void finished();void SecondsUpdate();public:int getValue(){return Seconds;}int Seconds;};请编辑您的问题并将其添加到那里。@eyllanesc donechangeconnect(Count,&Counter::SecondsUpdate,this,[=](int seconds){SetLabel(seconds);})
到connect(Count,&Counter::SecondsUpdate,this,&BaseWindow::SetLabel)
,更加优雅谢谢您的回复。看起来很棒!
connect(Count, &Counter::SecondsUpdate, this, [=]{ SetLabel(Count->Seconds) ;});
connect(Count, &Counter::SecondsUpdate, this, &BaseWindow::SetLabel);