【发布时间】:2015-07-20 07:53:10
【问题描述】:
我使用QStackedWidget 在 Qt 应用程序中处理多个窗口/窗体
根据this question.
我使用这种模式:
- 将所有小部件对象添加到 mainwindow.cpp 中的
QStackedWidget - 根据请求从子窗口获取信号以更改窗口
- mainwindow 替换窗口(它更新右侧槽中的 QStackedWidget)
我的问题:
这是正确的方法吗?我的应用程序中有很多窗口,并希望确保这是常见的最佳实践。 这种模式意味着我有指向主窗口中所有窗口的指针。
我的一段代码: 主窗口.cpp:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mnuWin = new Menu();
singlePulseWin = new SinglePulse();
repetitive = new Repetitive();
treatmentType = new TreatmentType();
//... and so on ....
connect(mnuWin,&Menu::updateMainWindowStackWidget,this,&MainWindow::onChangeWindowRequested);
connect(singlePulseWin,&SinglePulse::updateMainWindowStackWidget,this,&MainWindow::onChangeWindowRequested);
connect(repetitive,&Repetitive::updateMainWindowStackWidget,this,&MainWindow::onChangeWindowRequested);
connect(treatmentType,&TreatmentType::updateMainWindowStackWidget,this,&MainWindow::onChangeWindowRequested);
//... and so on ....
ui->pagesWidget->addWidget(mnuWin);
ui->pagesWidget->addWidget(singlePulseWin);
ui->pagesWidget->addWidget(repetitive);
ui->pagesWidget->addWidget(treatmentType);
//... and so on ....
ui->pagesWidget->setCurrentIndex(0);
}
void MainWindow::onChangeWindowRequested(int ind) //slot
{
ui->pagesWidget->setCurrentIndex(ind);
}
menu.cpp:
void Menu::on_btnMenuSinglePulse_clicked()
{
emit updateMainWindowStackWidget(1);
}
void Menu::on_btnMenuRepetitive_clicked()
{
emit updateMainWindowStackWidget(2);
}
void Menu::on_btnMenuBurst_clicked()
{
emit updateMainWindowStackWidget(3);
}
【问题讨论】:
-
取决于您的需要。如果一次只能看到一个“窗口”,这听起来是个不错的方法。如果您一次需要多个可见窗口,这不是可行的方法。
-
你看过
QTabWidget吗? -
您可以做的另一件事是创建一个辅助方法,称为
addForm(mnuWin, ...);,然后为每个表单页面调用它,然后执行必要的连接和ui->pagesWidget->addWidget(..)等等,什么是必要的。这将防止复制粘贴错误并缩短您的代码。 -
@Mailerdaimon 我不能使用多个窗口,因为我使用的 qt 嵌入式和 eglfs 插件只需要一个窗口。忘记提了。