python-3.x - PyQt5 中的多个页面
问题描述
所以我想在 PyQt5 中有多个页面;例如,当我单击一个按钮时,它会转换到另一个页面。这是我的代码。
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
Button = QPushButton("OK")
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(Button)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle('Buttons')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
我希望当我单击按钮时,它会转换到另一个页面,其中还有另一个按钮,如果我按下它将转换回初始页面。
解决方案
您可以QStackedWidget
为此使用,例如:
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout, QApplication, QStackedWidget, QLabel)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.stacked_widget.currentChanged.connect(self.set_button_state)
self.next_button.clicked.connect(self.next_page)
self.prev_button.clicked.connect(self.prev_page)
def initUI(self):
self.next_button = QPushButton('Next')
self.prev_button = QPushButton('Previous')
self.next_button.setEnabled(False)
self.prev_button.setEnabled(False)
self.stacked_widget = QStackedWidget()
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(self.prev_button)
hbox.addWidget(self.next_button)
vbox = QVBoxLayout()
vbox.addWidget(self.stacked_widget)
vbox.addLayout(hbox)
self.setLayout(vbox)
def set_button_state(self, index):
self.prev_button.setEnabled(index > 0)
n_pages = len(self.stacked_widget)
self.next_button.setEnabled( index % n_pages < n_pages - 1)
def insert_page(self, widget, index=-1):
self.stacked_widget.insertWidget(index, widget)
self.set_button_state(self.stacked_widget.currentIndex())
def next_page(self):
new_index = self.stacked_widget.currentIndex()+1
if new_index < len(self.stacked_widget):
self.stacked_widget.setCurrentIndex(new_index)
def prev_page(self):
new_index = self.stacked_widget.currentIndex()-1
if new_index >= 0:
self.stacked_widget.setCurrentIndex(new_index)
if __name__ == '__main__':
app = QApplication([])
ex = Example()
for i in range(5):
ex.insert_page(QLabel(f'This is page {i+1}'))
ex.resize(400,300)
ex.show()
app.exec()
另一种选择可能是使用QWizard
一个相当专业的类,该类旨在生成一个具有与许多程序用于安装的设置对话框相同的外观和感觉的对话框。
推荐阅读
- laravel - 如何在 Laravel 中成功付款后重定向到成功页面
- javascript - 将部分 XML 响应解析为 Postman 中的另一个请求
- flutter - 当我尝试登录我的应用程序时,我一直面临这个不安全的 http 错误
- opengl - 在 Libgdx/Lwjgl 中加载生成的纹理数据是不确定的
- mysql - SQL查询根据train_number检索数据
- c# - C#在特定文件夹问题下添加引用
- nginx - 关于nginx位置优先级的困惑
- android - Android Room 垃圾邮件同时插入记录很慢
- email - Google Workspace 重定向不存在的电子邮件地址
- php - Symfony 5:/lucky/number 应用程序的 404 页面