由于您不提供MRE,因此我将从头开始提供解决方案。
解决方案是使用 QButtonGroup 添加与 id 关联的按钮,然后使用 buttonClicked 信号发送按下按钮的 id 信息,该信息应设置为 QStackedWidget 的 currentIndex。
import sys
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.title_label = QtWidgets.QLabel(
"BANK OF BRAAVOS", alignment=QtCore.Qt.AlignCenter
)
self.balance_inquiry_button = QtWidgets.QToolButton(text="Balance Inquiry")
self.transaction_button = QtWidgets.QToolButton(text="Transaction")
self.balance_sheet_button = QtWidgets.QToolButton(text="Balance Sheet")
self.support_button = QtWidgets.QToolButton(text="Support")
self.stacked_widget = QtWidgets.QStackedWidget()
self.stacked_widget.addWidget(
QtWidgets.QLabel("Balance Inquiry", alignment=QtCore.Qt.AlignCenter)
)
self.stacked_widget.addWidget(
QtWidgets.QLabel("Transaction", alignment=QtCore.Qt.AlignCenter)
)
self.stacked_widget.addWidget(
QtWidgets.QLabel("Balance Sheet", alignment=QtCore.Qt.AlignCenter)
)
self.stacked_widget.addWidget(
QtWidgets.QLabel("Support", alignment=QtCore.Qt.AlignCenter)
)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.title_label)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(self.balance_inquiry_button)
hlay.addWidget(self.transaction_button)
hlay.addWidget(self.balance_sheet_button)
hlay.addWidget(self.support_button)
lay.addLayout(hlay)
lay.addWidget(self.stacked_widget)
self.group_button = QtWidgets.QButtonGroup()
for i, button in enumerate(
(
self.balance_inquiry_button,
self.transaction_button,
self.balance_sheet_button,
self.support_button,
)
):
self.group_button.addButton(button, i)
self.group_button.buttonClicked[int].connect(
self.stacked_widget.setCurrentIndex
)
self.resize(640, 480)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())