Qt不能多次执行线程

Qt can t execute thread multiple times

本文关键字:执行 线程 不能 Qt      更新时间:2023-10-16

我正在尝试连续运行一个线程。在我的情况下,每次线程完成执行时,我都无法第二次启动它。我浏览了类函数,看看是否会有类似 restart(( 之类的东西,但事实似乎并非如此。

有人可以告诉我我可能错过了什么吗?

webcamClass::webcamClass(QObject *parent) : QObject(parent)
{
recognizePerson=false;
//setup recognition thread
recognitionThread = new QThread(this);
recognitionClObj = new recognitionClass();
connect( recognitionThread, SIGNAL(started()), recognitionClObj,       SLOT(recognizePerson()) );
recognitionClObj->moveToThread(recognitionThread);
}
void webcamClass:: getVideoFrame()
{
qDebug()<<"this is the webcam thread";
static cv::VideoCapture cap(CV_CAP_ANY);
cv::Mat imgFrame;
if( !cap.isOpened() )
{
qDebug()<< "Could not initialize capturing...n";
}
while(1)
{
cap >> imgFrame;
cv::cvtColor(imgFrame, imgFrame, CV_BGR2RGB);
QImage img;
img = QImage((uchar*)imgFrame.data, imgFrame.cols,       imgFrame.rows, QImage::Format_RGB888);
QPixmap pixmap = QPixmap::fromImage(img);
emit gottenVideoFrame(pixmap);
if(recognizePerson==true)
{
recognitionThread->start();
qDebug()<<"started recognition thread";
}
cv::waitKey(100);
}
}
int recognitionClass::recognizePerson()
{
qDebug()<<"recognizing person";
}

生成的输出:

this is the webcam thread
started recognition thread
recognizing person
started recognition thread
started recognition thread
started recognition thread
started recognition thread
started recognition thread
started recognition thread
started recognition thread
started recognition thread

如您所见,句子"识别人"仅被打印 1,而我希望它像"启动识别线程"一样被打印多次

理想情况下,我希望线程等待直到它收到新数据。它应该这样做 20 次,然后返回新数据。

connect( recognitionThread, SIGNAL(started(((, recognitionClObj, SLOT(recognizePerson(((,Qt::D irectConnection(;

您可以尝试在您的连接中添加Qt::D irectConnection

您的 recognitionThread 已经启动,因此每次进一步调用 start 都不会执行任何操作,也不会生成任何新的启动信号。如果你想让你的识别类做新的工作,你必须将另一个信号连接到插槽识别人。 所以在你的网络摄像头类中定义一个信号

signal:
void doRecognize();

添加第二个连接到您的网络摄像头类信号到识别类

connect(this, SIGNAL(doRecognize()), recognitionClObj, SLOT(recognizePerson()));

而不是识别线程>start(( 问题

emit doRecognize();