Python 图形界面设计:PyQt6简单实现标签页面切换
实现一个简单的功能,ping列表的内容,把ping结果展示,ping不通时会有声音提示。
这个页面是QWidget
页面,不能提供更多的窗口和功能,今天把QWidget
改成QMainWindow
,QMainWindow
可以增加菜单,和状态栏等功能,可以在窗口内加QWidget
页面。在此窗口基础上,添加几个页面,底部几个按钮(PushButton
)相当于页面标签,进行切换使用。下面的三个按钮,只有第一个做了关联,其他两个按钮直接显示一个标签(QLabel
),实现后大概如图:
页面切换使用QStackedWidget
,QStackedWidget
可以填中多个页面,通过setCurrentIndex(0)
来设置激活那个页面。每一个页面的按钮不能共用,实际上是三个页面,每个页面有3个按钮,每个页面有2个按钮的动作做了关联。
self.button1_2.clicked.connect(self.show_layout2) self.button1_3.clicked.connect(self.show_layout3) self.button2_1.clicked.connect(self.show_layout1) self.button2_3.clicked.connect(self.show_layout3) self.button3_1.clicked.connect(self.show_layout1) self.button3_2.clicked.connect(self.show_layout2)
切换页面代码
def show_layout1(self): self.central_widget.setCurrentIndex(0) self.statusBar().showMessage('仪器设备连通扫描')
实现这个功能应该有更好的方案,这个也不算是正经的页面标签页。为了实现这个功能,重复代码一堆。
self.central_widget = QStackedWidget() self.setCentralWidget(self.central_widget) self.layout1 = QVBoxLayout() self.layout2 = QVBoxLayout() self.layout3 = QVBoxLayout() self.widget1 = QWidget() self.widget2 = QWidget() self.widget3 = QWidget() self.widget1.setLayout(self.layout1) self.widget2.setLayout(self.layout2) self.widget3.setLayout(self.layout3) self.central_widget.addWidget(self.widget1) self.central_widget.addWidget(self.widget2) self.central_widget.addWidget(self.widget3)
layout1、2、3对应这三个页面,后面再写代码,填另组件,直接填加即可:
self.layout1.addWidget(self.table_widget) self.layout1.addLayout(hbox_layout1)
另外我还想实现些汇图功能,可能通过PyQt6与Matplotlib结合,实现绘图。
import sys from PyQt6 import ( QtCore, QtWidgets, ) # import PyQt6 before matplotlib import matplotlib import pandas as pd from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg from matplotlib.backends.backend_qtagg import ( NavigationToolbar2QT as NavigationToolbar, ) from matplotlib.figure import Figure matplotlib.use("QtAgg") class MplCanvas(FigureCanvasQTAgg): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) super().__init__(fig) class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() # Create the maptlotlib FigureCanvasQTAgg object, # which defines a single set of axes as self.axes. sc = MplCanvas(self, width=5, height=4, dpi=100) # Create our pandas DataFrame with some simple # data and headers. df = pd.DataFrame( [ [0, 10], [5, 15], [2, 20], [15, 25], [4, 10], ], columns=["A", "B"], ) # plot the pandas DataFrame, passing in the # matplotlib Canvas axes. df.plot(ax=sc.axes) # Create toolbar, passing canvas as first parameter, parent (self, the MainWindow) as second. toolbar = NavigationToolbar(sc, self) layout = QtWidgets.QVBoxLayout() layout.addWidget(toolbar) layout.addWidget(sc) # Create a placeholder widget to hold our toolbar and canvas. widget = QtWidgets.QWidget() widget.setLayout(layout) self.setCentralWidget(widget) self.show() app = QtWidgets.QApplication(sys.argv) w = MainWindow() app.exec()
有了这些基础,还有更多玩法。