gpt4 book ai didi

c++ - 避免 GUI 在多线程操作时卡住

转载 作者:行者123 更新时间:2023-11-30 00:50:37 27 4
gpt4 key购买 nike

我有一个 Qt GUI 类 preferencesWindow,显然,它负责处理用户首选项。我有一些字段管理与数据库服务器的连接。当留下一个字段时,调用 dbsChanged() 方法。以下是我设法编写的一些代码:

void preferencesWindow::dbsChanged() {
QFuture<QStringList> loader = run(this, &preferencesWindow::get_databases);
QStringList databases = loader.result();

if (databases.length()) {
this->ui.database->show();
this->ui.nodb_label->hide();
this->ui.database->clear();
this->ui.database->addItems(databases);
this->ui.okButton->setDisabled(false);
this->ui.validationStatus->setPixmap(QPixmap(":/icon/tick.png"));
} else {
this->ui.database->hide();
this->ui.nodb_label->show();
this->ui.okButton->setDisabled(true);
this->ui.validationStatus->setPixmap(QPixmap(":/icon/error.png"));
}
}
QStringList preferencesWindow::get_databases() {
QSqlDatabase test_connection;
if (QSqlDatabase::contains("PREFEREMCES_LIVE_TEST_CONNECTION"))
test_connection = QSqlDatabase::database("PREFEREMCES_LIVE_TEST_CONNECTION");
else test_connection = QSqlDatabase::addDatabase("QMYSQL", "PREFEREMCES_LIVE_TEST_CONNECTION");
test_connection.setHostName(this->ui.serverAddress->text());
test_connection.setUserName(this->ui.username->text());
test_connection.setPassword(this->ui.password->text());
test_connection.setDatabaseName(this->ui.database->currentText());
test_connection.setPort(this->ui.serverPort->value());

test_connection.open();
qDebug() << "Error: " << test_connection.lastError();
QSqlQuery show_databases = test_connection.exec("show databases");
QStringList databases;
while (show_databases.next()) {
databases.append(show_databases.value(0).toString());
}
QSqlDatabase::removeDatabase("PREFERENCES_LIVE_TEST_CONNECTION");
return databases;
}

由于 get_databases 可能需要很长时间,我认为将其放入一个单独的线程中,如您在这两行中所见:

QFuture<QStringList> loader = run(this, &preferencesWindow::get_databases);
QStringList databases = loader.result();

可以解决问题。它在一个单独的线程上运行,但它仍然卡住 GUI(在工作时)。

我应该如何重写整个过程?我虽然有一些解决方案,但我不太确定它们的性能,我不想无用功...

最佳答案

它卡住了 GUI,因为即使 get_databases 调用在一个单独的线程中,您仍然等待导致卡住的结果。

我不知道如何在 Qt 中做到这一点,但正常的做法是打开一个对话框,上面写着“请稍候”或带有取消按钮的东西,然后让工作线程向父线程发送一个信号(GUI ) 线程完成后。

关于c++ - 避免 GUI 在多线程操作时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24446809/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com