How To Change Window/widget With Pyqt5 Using .ui Files?
Solution 1:
What you need to do is to create separate widgets (not windows). While this is already covered in other similar questions (like this, I'll answer anyway due to the different files request.
The solution is still the same, using a QStackedWidget, that allows you to switch between different widgets that occupy the same part of the window, similarly to what QTabWidget does, but without the tab bar.
First, you need to create a main window in designer, add a QStackedWidget there and ensure that you remove all of its pages (right click on the stacked widget, and select "Delete" in the "Page x of x" sub menu). Then create separate widgets (just select "Widget" in the dialog that appears when creating a new form) for each page.
Finally, use loadUi
on the main window and on each child widget.
I'll recommend you to keep the logic of the page switching in the code of the main window, instead of having it in the different pages, as it's a better and cleaner approach having a "parent" controller when dealing with this situations.
pages.py:
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from first import First
from second import Second
classMainWindow(QMainWindow):
def__init__(self):
super().__init__()
uic.loadUi('pages.ui', self)
self.first = First()
self.stackedWidget.addWidget(self.first)
self.first.change_btn.clicked.connect(self.go_to_second)
self.second = Second()
self.stackedWidget.addWidget(self.second)
self.second.change_btn.clicked.connect(self.go_to_first)
defgo_to_first(self):
self.stackedWidget.setCurrentIndex(0)
defgo_to_second(self):
self.stackedWidget.setCurrentIndex(1)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
first.py
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
classFirst(QWidget):
def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
uic.loadUi('first.ui', self)
second.py
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
classSecond(QWidget):
def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
uic.loadUi('second.ui', self)
There is also the possibility of using QWizard, but it's usually suggested for more complex cases than yours.
Post a Comment for "How To Change Window/widget With Pyqt5 Using .ui Files?"