简体   繁体   English

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

[英]How I can close dialog, from another thread? Qt

I want to handle my button in this way: 我想以这种方式处理按钮:

  1. Change text on label (somethink like "Please wait...") 更改标签上的文字(例如“请稍候...”)
  2. Download some data from database 从数据库下载一些数据
  3. When downloading is done, close dialog where is this button. 下载完成后,关闭对话框,该按钮在哪里。

When I do this: 当我这样做时:

void LoadingDialog::on_pushButton_clicked()
{
m_ui->labelStatus->setText("Pobieranie wysyłek...");

if(m_methodToDo == MethodToDo::LoadShipment)
{
    if(DataManager::getManager()->loadShipments())
    {
        this->close();
    }
}
}

the label hasn't changed text, is few second of lag (is downloading few k records) and dialog is closing. 标签未更改文本,延迟几秒钟(正在下载几千条记录)并且对话框关闭。

When I try this: 当我尝试这个:

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();
});
}

the label has change text - it's ok is few second of lag - it's ok but dialog isn't closed, and my application throws exception : 标签上有更改文本-没问题,只是几秒钟的延迟-没关系,但对话框没有关闭,我的应用程序抛出异常:

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

Any suggestion? 有什么建议吗?

First, changeStatus is not blocking, so do not run it on another thread. 首先,changeStatus不会阻塞,因此不要在另一个线程上运行它。 On the other hand if you want to invoking a slot from another thread you can use QMetaObject::invokeMethod() : 另一方面,如果要从另一个线程调用插槽,则可以使用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();
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM