下面是一个模态对话框的显示效果:
对话框的完整代码如下:
头文件:
class ModalDialog : public QDialog
{
Q_OBJECT
public:
ModalDialog(QWidget* parent = nullptr);
~ModalDialog();
void setContentText(const QString& text);
signals:
void clickedOKButton(void);
void clickedCannelButton(void);
private:
QLabel* m_pContentLabel = nullptr;
};
cpp文件
ModalDialog::ModalDialog(QWidget* parent)
:QDialog(parent)
{
QVBoxLayout* mainLayout = new QVBoxLayout(this);
m_pContentLabel = new QLabel();
m_pContentLabel->setMinimumSize(200, 120);
m_pContentLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
mainLayout->addWidget(m_pContentLabel);
// 添加按钮
QPushButton* okButton = new QPushButton("确定");
QPushButton* cannelButton = new QPushButton("取消");
QHBoxLayout* bottomLayout = new QHBoxLayout();
bottomLayout->addStretch();
bottomLayout->addWidget(okButton);
bottomLayout->addWidget(cannelButton);
mainLayout->addLayout(bottomLayout);
// 连接信号
QObject::connect(okButton, &QPushButton::clicked, this, &ModalDialog::clickedOKButton);
QObject::connect(cannelButton, &QPushButton::clicked, this, &ModalDialog::clickedCannelButton);
}
ModalDialog::~ModalDialog()
{
}
void ModalDialog::setContentText(const QString& text)
{
m_pContentLabel->setText(text);
}
整体对话框是继承自QDialog,界面实现内容比较简单。
接下来是调用部分:
void MainWindow::onClickedModalButton(void)
{
ModalDialog dialog(this);
dialog.setContentText("模态对话框");
QObject::connect(&dialog, &ModalDialog::clickedOKButton, &dialog, &ModalDialog::accept);
QObject::connect(&dialog, &ModalDialog::clickedCannelButton, &dialog, &ModalDialog::reject);
if (dialog.exec() == ModalDialog::Accepted)
m_pTextEdit->append("Modal: Clicked OK Button");
else
m_pTextEdit->append("Modal: Clicked Cannel Button");
m_pTextEdit->append("Closed Modal Window");
}
点击 模态对话框 后,调用这部分代码
下面是非模态对话框的展示效果:
其中对话框的内容部分与上面的模态相同,调用 部分有所差异:
void MainWindow::onClickedModelessButton(void)
{
ModalDialog *dialog = new ModalDialog(this);
QObject::connect(dialog, &ModalDialog::clickedOKButton, \
[&]()->void{m_pTextEdit->append("Modeless: Clicked OK Button");});
QObject::connect(dialog, &ModalDialog::clickedCannelButton, \
[&]()->void{m_pTextEdit->append("Modeless: Clicked Cannel Button");});
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setContentText("非模态对话框");
dialog->show();
m_pTextEdit->append("Created Modeless Window");
}
下面时一个半模态的效果示例:
调用部分代码如下:
void MainWindow::onClickedHalfModalButton(void)
{
ModalDialog *dialog = new ModalDialog(this);
QObject::connect(dialog, &ModalDialog::clickedOKButton, \
[&]()->void{m_pTextEdit->append("Half Modal: Clicked OK Button");});
QObject::connect(dialog, &ModalDialog::clickedCannelButton, \
[&]()->void{m_pTextEdit->append("Half Modal: Clicked Cannel Button");});
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setModal(true);
dialog->setContentText("半模态对话框");
dialog->show();
m_pTextEdit->append("Created Half Modal Window");
}