我有一个qt和cpp应用程序,它在create按钮上创建线程,并在用户指定的特定启动时间内运行它们。它列出了创建到应用程序中的QListWidget中的线程对象,其中包含一些随机生成的id。我可以选择和删除QListWidget项目,如下所示。
void MainWindow::on_stopPushButton_clicked()
{
qDebug() << mythread->threadIdGenerator();
QList<QListWidgetItem*> items = ui->threadWithId->selectedItems();
foreach(QListWidgetItem* item, items){
ui->threadWithId->removeItemWidget(item);
delete item; // Qt documentation warnings you to destroy item to effectively remove it from QListWidget.
}
}此删除操作只是从应用程序的UI ( QListWidget )中删除条目,但从QListWidget中删除的线程仍在应用程序中运行。
我的问题是如何从应用程序的UI中删除QListWidget来终止这个线程?或者有什么方法可以在从UI中选择之后获取这个线程对象并删除它。
更新
void MainWindow::on_createNewThreadButton_clicked()
{
qDebug(" in create new thread slot");
mythread = new MyThread(this);
mythread->threadOccuranceTime = ui->insertThreadTimeoutHere->text().toInt();
mythread->start();
myThreadListCreatedObjects.append(mythread);
connect(mythread, SIGNAL(signalForThreadMessage(int)), this, SLOT(displayThreadMessages(int)));
connect(mythread, SIGNAL(sendThreadId(int)), this, SLOT(displayThread(int)));
}MyThread.cpp
int MyThread::threadIdGenerator()
{
qDebug(" in threadIdGenerator function");
// qDebug() << 1 + (rand() % 100);
srand(time(0));
return 1 + (rand() % 100);
}
void MyThread::run()
{
this->threadId = 0;
qDebug() << this->threadId;
qDebug(" in run function for the thread");
this->threadId = this->threadIdGenerator();
qDebug(" id inside the run method of thread");
qDebug() << threadId;
emit sendThreadId(threadId);
while (1) {
msleep(this->threadOccuranceTime);
emit signalForThreadMessage(this->threadId);
}
}发布于 2022-06-03 04:53:04
我使用QList存储创建的所有线程,当在QLIstWidget中选择一个项时,我尝试使用该id属性获取线程,然后终止它,然后从UI中删除,如下所示。
void MainWindow::on_stopPushButton_clicked()
{
QList<QListWidgetItem*> items = ui->threadWithId->selectedItems();
foreach(QListWidgetItem* item, items){
qDebug() << "the item selected to delete";
qDebug() << item->text();
ui->threadWithId->removeItemWidget(item);
QString selected = item->text();
QString subString = selected.mid(0,2);
qDebug() << "subString = ";
qDebug() << subString;
for(MyThread *sp:myThreadListCreatedObjects){
qDebug() << "thread id = ";
qDebug() << sp->threadId;
if(sp->threadId == subString.toInt()){
qDebug() << "subString = ";
qDebug() << subString;
sp->terminate();
delete sp;
}
}
delete item; // Qt documentation warnings you to destroy item to effectively remove it from QListWidget.
}
}我不确定这是正确的做法,但它的工作方式。欢迎任何更好的解决方案:)。
https://stackoverflow.com/questions/72464549
复制相似问题