如何从另一个线程关闭对话框?QT

How I can close dialog, from another thread? Qt

本文关键字:对话框 QT 线程 另一个      更新时间:2023-10-16

我想以这种方式处理我的按钮:

  1. 更改标签上的文本(如"请等待...",例如"请等待...")
  2. 从数据库下载一些数据
  3. 下载完成后,关闭对话框此按钮在哪里。

当我这样做时:

void LoadingDialog::on_pushButton_clicked()
{
m_ui->labelStatus->setText("Pobieranie wysyłek...");
if(m_methodToDo == MethodToDo::LoadShipment)
{
    if(DataManager::getManager()->loadShipments())
    {
        this->close();
    }
}
}

标签没有更改文本,是滞后的几秒钟(下载k记录很少),并且对话框正在关闭。

当我尝试一下时:

void LoadingDialog::changeStatus(QString status)
{
m_ui->labelStatus->setText(status);
}
bool LoadingDialog::load()
{
if(m_methodToDo == MethodToDo::LoadShipment)
{
    if(DataManager::getManager()->loadShipments())
    {
        this->close();
    }
}
}
void LoadingDialog::on_pushButton_clicked()
{
QFuture<void> future3 = QtConcurrent::run([=]() {
    changeStatus("Pobieranie wysyłek..."); // "Downloading.."
});
QFuture<void> future = QtConcurrent::run([=]() {
    load();
});
}

标签具有更改文字 - 还可以是滞后的几秒 - 还可以但是对话框没有关闭,我的应用程序会引发例外:

Cannot send events to objects owned by a different thread. Current thread 229b1178. Receiver 'Dialog' (of type 'LoadingDialog') was created in thread 18b00590

任何建议?

首先,Changestatus没有阻止,因此请勿在另一个线程上运行。另一方面,如果您想从另一个线程调用插槽,则可以使用QMetaObject::invokeMethod()

bool LoadingDialog::load()
{
    if(m_methodToDo == MethodToDo::LoadShipment)
        if(DataManager::getManager()->loadShipments())
            QMetaObject::invokeMethod(this, "close", Qt::QueuedConnection);
}
void LoadingDialog::on_pushButton_clicked()
{
    changeStatus("Pobieranie wysyłek..."); // "Downloading.."
    QFuture<void> future = QtConcurrent::run([=]() {
        load();
    });
}