Вопрос

I have a button on my first Qt window. When the button is clicked, the current window's ui should get changed to that of a different ui file. Right now, when I click the button, a new window opens, but the old window is still open. Is there a way to replace the current window's contents with different content? or is better to simply open another window and destroy the first window?

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    otherWindow = new OtherWindow();
    otherWindow->show();
}
Это было полезно?

Решение

It is theoretically possible to replace one UI with another.

You will need to follow the following steps:

  1. Destroy all the child objects created by the first UI in the constructor
  2. Create an instance of the new UI
  3. Run setupUi(this) on the new UI

As I said, this is theoretical. It's is far from practical though because your UI classes will have to be derived from the same base class and all slots relating to your first UI might behave strangely if connected to your new UI.

What I could suggest is that you follow the Model-View-Controller (MVC) design pattern. Here's one suggestion, others may have better ones.

  1. Create a derived class of QWidget to function as your Controller class. Design all the signals and slots that will handle all the user events generated by the View.
  2. Design the UI in QtDesigner and make this a private member of your Controller class. Let is build all the UI elements in the Controller class' constructor and then connect all the signals and slots. This will function as the View in the design pattern.
  3. If you need some persistent data, either create a class or collection of classes to function as the Model, or pass one to your Controller class. Use this to set all values of child widgets in your View UI.
  4. Pass the Controller QWidget to the QMainWindow function setCentralWidget() to set it as the UI that the user can see.
  5. Repeat steps 1-4 for each different UI that you might need.
  6. When you need to swap out UIs, just use the setCentralWidget() on QMainWindow to change to the appropriate UI.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top