一. 模态

模态: 背景不可选择

打开窗口

  • 启动模态窗口
  1. #include "qdialogsetsize.h"
  2. QDialogSetSize *dlg = new QDialogSetSize(this);
  3. // 设置固定大小
  4. Qt::WindowFlags flags = dlg->windowFlags();
  5. dlg->setWindowFlags(flags | Qt::MSWindowsFixedSizeDialogHint);
  6. dlg->exec();

二. 非模态

非模态: 背景也可以选择

打开窗口

  • 启动非模态窗口
  1. QDialogLocate *dlgLocate = new QDialogLocate(this);
  2. dlgLocate->setAttribute(Qt::WA_DeleteOnClose); // 在关闭的时候自动delete
  3. Qt::WindowFlags flags = dlgLocate->windowFlags(); // 窗口显示在最顶层
  4. dlgLocate->setWindowFlags(flags | Qt::WindowStaysOnTopHint);
  5. dlgLocate->show();

三. 与窗口交互

有两种方法:

  • 通过函数调用,然后通过自己的函数来给自己的控件设置
  • 通过信号与槽

1. 通过函数调用

  • 窗口:

qdialogsetsize.h:

  1. public:
  2. // 获取UI的值
  3. int columnCount();
  4. int rowCount();
  5. // 设置UI的默认值
  6. void setRowAndColumn(int row, int column);

qdialogsetsize.cpp:

  1. int QDialogSetSize::columnCount()
  2. {
  3. return ui->spinBoxColumn->value();
  4. }
  5. int QDialogSetSize::rowCount()
  6. {
  7. return ui->spinBoxRow->value();
  8. }
  9. void QDialogSetSize::setRowAndColumn(int row, int column)
  10. {
  11. ui->spinBoxColumn->setValue(column);
  12. ui->spinBoxRow->setValue(row);
  13. }

并且设置btnOK和btnCancel的click()的槽分别为: accept(), reject()

  • 调用:
  1. #include "qdialogsetsize.h"
  2. QDialogSetSize *dlg = new QDialogSetSize(this);
  3. dlg->setRowAndColumn(theModel->rowCount(), theModel->columnCount());
  4. int ret = dlg->exec(); // 启动模态窗口
  5. if (ret == QDialog::Accepted) { // 获取点的是OK按钮
  6. int row = dlg->rowCount();
  7. int column = dlg->columnCount();
  8. theModel->setColumnCount(column);
  9. theModel->setRowCount(row);
  10. }
  11. delete dlg;

子窗口获取父窗口对象方法:

  1. MainWindow *parentWin = (MainWindow *)parentWidget(); // 获取父窗口
  2. parentWin->setActLocateEnable(true); // 调用父窗口函数

2. 通过子窗口与父窗口的singal,slot:

  1. private slots:
  2. void setACellText(int row, int col, QString text);
  1. connect(dlgLocate, SIGNAL(changeCellText(int,int,QString)),
  2. this, SLOT(setACellText(int,int,QString)));
  1. signals:
  2. void changeCellText(int, int, QString);
  1. emit changeCellText(row, col, ui->lineEdit->text());