我如何从另一个线程关闭对话框? Qt的

问题描述 投票:1回答:1

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

  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

有什么建议吗?

c++ qt qthread qtconcurrent qfuture
1个回答
0
投票

首先,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();
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.