qt无边框QDialog->exec();父窗口的消息循环被阻塞了不允许使用非模态对话框,此时模态窗口以外的区域模态窗口抖动给出详细的代码实现
时间: 2025-01-05 07:41:43 浏览: 214
在Qt中,当你使用`QDialog::exec()`方法显示一个模态对话框时,父窗口的消息循环会被阻塞。这意味着在模态对话框关闭之前,用户无法与父窗口进行交互。如果你希望在模态对话框显示时,父窗口仍然能够响应某些事件(例如动画或其他视觉效果),你可以使用`QTimer`来实现这一点。
以下是一个详细的代码实现示例:
```cpp
#include <QApplication>
#include <QDialog>
#include <QTimer>
#include <QLabel>
#include <QVBoxLayout>
class ModalDialog : public QDialog {
public:
ModalDialog(QWidget *parent = nullptr) : QDialog(parent) {
setWindowTitle("模态对话框");
setFixedSize(300, 200);
QLabel *label = new QLabel("这是一个模态对话框", this);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(label);
setLayout(layout);
}
};
class MainWindow : public QWidget {
public:
MainWindow(QWidget *parent = nullptr) : QWidget(parent) {
setWindowTitle("主窗口");
setFixedSize(400, 300);
QLabel *label = new QLabel("主窗口", this);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(label);
setLayout(layout);
QTimer::singleShot(1000, this, &MainWindow::showModalDialog);
}
void showModalDialog() {
ModalDialog *dialog = new ModalDialog(this);
dialog->setModal(true);
dialog->show();
// 使用QTimer来模拟主窗口的某些操作
QTimer::singleShot(500, this, [dialog]() {
// 在这里可以执行一些操作,例如动画或其他视觉效果
dialog->setWindowTitle("更新后的标题");
});
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
```
在这个示例中,`MainWindow`类在构造函数中使用`QTimer::singleShot`方法在1秒后调用`showModalDialog`方法。`showModalDialog`方法创建一个`ModalDialog`实例并显示它,同时使用`QTimer::singleShot`方法在500毫秒后更新模态对话框的标题。
这样可以确保在模态对话框显示时,主窗口仍然能够响应某些事件,例如动画或其他视觉效果。
阅读全文