Как я могу остановить поток, работающий в моем классе диалога, из моего mainWindow - PullRequest
0 голосов
/ 05 августа 2020

Мое главное окно выглядит так

enter image description here

it is a qlistwidget with some Job items, whenever any job item is clicked , it shows up the QDialogbox which looks like this.

введите описание изображения здесь

QDialog имеет виджет списка и кнопку показа, всякий раз, когда нажимается кнопка показа, список из 10000 возможных сотрудников будет отображаться в виджете Qlist, и эти сотрудники рассчитываются этой функцией, которая находится в thread3.

    void KeyComd::Print_Descendants_key(IUIAutomation* pUIAutomation, IUIAutomationElement* pParent, int indent)
{
    ///Function which appends 1000 list-items in a QListWidget called "elements_listwidget" in my QDialog.
}

Обычный поток:

  1. я щелкаю элемент (Carwa sh задание) в главном окне
  2. появляется окно QDialog , я нажимаю кнопку show, и появляется список из 10 000 возможных сотрудников.
  3. Я выбираю разъем сотрудника в QDialog и нажимаю «ОК».
  4. элемент главного окна изменяется на «Работа по мойке автомобилей, назначенная: Джек, рост 5'10, вес 86 дюймов

Мой вопрос в том, что на шаге 3, даже когда все 10000 элементов еще не загружены, и я нахожу предпочтительного сотрудника в первых 500 элементах списка, я выбираю его и нажмите «ОК» в диалоговом окне, элемент в главном окне все еще не изменяется, пока не завершится выполнение thread3, могу ли я принудительно остановить или завершить thread3? так что, когда я нажимаю "ОК", thread3 останавливается, и элемент в главном окне изменяется.

Это мой файл диалога cpp с именем Keycomd. cpp

#include "KeyComd.h"
#include "ui_KeyComd.h"
#include <QtCore>
#include <QtGui>
#include <vector> 
#include<QDebug>
#include "ExecutionContext.h"
#include "XMLParser.h"
#include "Logger.h"
#include "BlockCommand.h"
#include "UIAElementUtils.h"

ExecutionContext exc;
QStringList refreshed_elements;

KeyComd::KeyComd(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
    HRESULT hr = exc.init();    
}

KeyComd::~KeyComd()
{
}
void KeyComd::on_showbutton_clicked()
{
    ui.elements_listwidget->clear();
    desktop_elements.clear();

    std::thread thread3(&KeyComd::Print_step, this); // Here it calls a thread, because of this thread ,the execution of "Print_Descendants_key" function happens in a separate thread from main thread
    thread3.detach();
}

void KeyComd::Print_step()
{
    Print_Descendants_key(exc.pUIAutomation, nullptr, 0);
}

void KeyComd::Print_Descendants_key(IUIAutomation* pUIAutomation, IUIAutomationElement* pParent, int indent)
{
    ///Function which appends 10000 list-items in a QListWidget called "elements_listwidget" in my QDialog.
}

мое главное окно. cpp код:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "XMLParser.h"
#include "ExecutionContext.h"
#include "Logger.h"
#include "BlockCommand.h"
#include "UIAElementUtils.h"
#include <thread>
#include <iostream>
#include <QtWidgets/qapplication.h>
#include <QtCore>
#include <QtGui>
#include <sstream>
#include <QtWidgets/qmessagebox.h>
#include <QtWidgets/qlistwidget.h>
#include <string>
#include <string.h>
#include <cstring>
#include <chrono>
#include <QCloseEvent>
#include "Header.h"
#include <map>
#include <QtWidgets/qinputdialog.h>
#include <vector> 
#include "dragsupport.h"
#include "KeyComd.h"


ExecutionContext exContext;

using namespace std; 

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    populatemaps();
    ui->setupUi(this);
 
    HRESULT hr = CoInitializeEx(NULL, NULL);
    ExecutionContext exContext;
    hr = exContext.init();
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_xml_scripts_textbox_itemDoubleClicked(QListWidgetItem* item)
{
        KeyComd keyComd;
        keyComd.exec();

        if (keyComd.result() == QDialog::Accepted) //when i click okay,the code inside this block gets executed
        {                   
           // Here when okay is clicked, i want to check if thread3 is still running and if it is then stop/terminate the thread3 which is in KeyComd.cpp file 
           
           ui->qlistwidget->additem("Car washing Job assigned to: Jack , height 5'10, weight 86, age 21");
        }
}

1 Ответ

1 голос
/ 05 августа 2020

Используйте QThread в главном окне, затем переместите объект QDialog в этот новый поток. Присоедините сигнал accepted вашего объекта QDialog к слоту quit в объекте QThread, который закроет поток. Я добавил приведенный ниже код с изменениями.

Главное окно

#include <QThread>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "XMLParser.h"
#include "ExecutionContext.h"
#include "Logger.h"
#include "BlockCommand.h"
#include "UIAElementUtils.h"
#include <thread>
#include <iostream>
#include <QtWidgets/qapplication.h>
#include <QtCore>
#include <QtGui>
#include <sstream>
#include <QtWidgets/qmessagebox.h>
#include <QtWidgets/qlistwidget.h>
#include <string>
#include <string.h>
#include <cstring>
#include <chrono>
#include <QCloseEvent>
#include "Header.h"
#include <map>
#include <QtWidgets/qinputdialog.h>
#include <vector> 
#include "dragsupport.h"
#include "KeyComd.h"


ExecutionContext exContext;

using namespace std; 

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    populatemaps();
    ui->setupUi(this);
 
    HRESULT hr = CoInitializeEx(NULL, NULL);
    ExecutionContext exContext;
    hr = exContext.init();
 // QThread dialog_thread; move this to header
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_xml_scripts_textbox_itemDoubleClicked(QListWidgetItem* item)
{
        KeyComd keyComd;
        keyComd.moveToThread(&dialog_thread);
        connect(&keyComd, &QDialog::Accepted, &dialog_thread, &QThread::quit);
        dialog_thread.start();
        keyComd.exec();        
        
        if (keyComd.result() == QDialog::Accepted) //when i click okay,the code inside this block gets executed
        {                   
           // Here when okay is clicked, i want to check if thread3 is still running and if it is then stop/terminate the thread3 which is in KeyComd.cpp file 
           ui->qlistwidget->additem("Car washing Job assigned to: Jack , height 5'10, weight 86, age 21");   
           emit keyComd.accepted();
        }
}

Диалоговое окно

#include "KeyComd.h"
#include "ui_KeyComd.h"
#include <QtCore>
#include <QtGui>
#include <vector> 
#include<QDebug>
#include "ExecutionContext.h"
#include "XMLParser.h"
#include "Logger.h"
#include "BlockCommand.h"
#include "UIAElementUtils.h"

ExecutionContext exc;
QStringList refreshed_elements;

KeyComd::KeyComd(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
    HRESULT hr = exc.init();
}

KeyComd::~KeyComd()
{
}
void KeyComd::on_showbutton_clicked()
{
    ui.elements_listwidget->clear();
    desktop_elements.clear();
    this->Print_Descendants_key();
}

void KeyComd::Print_step()
{
    Print_Descendants_key(exc.pUIAutomation, nullptr, 0);
}

void KeyComd::Print_Descendants_key(IUIAutomation* pUIAutomation, IUIAutomationElement* pParent, int indent)
{
    ///Function which appends 10000 list-items in a QListWidget called "elements_listwidget" in my QDialog.
}
...