小能豆

PySide 通过事件切换小部件?

py

我搞不懂。我希望能够根据按钮点击等事件来交换 QWidget,但我遗漏了一些东西,而且我无法找到任何与以下代码类似的示例。我想要做的是单击顶部按钮之一,然后让下面的小部件在 QCalendar 或 QtextEdit 之间切换。我哪里做错了?

谢谢!

#!/usr/bin/python
import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        hbox = QtGui.QHBoxLayout(self)
        widget = QtGui.QCalendarWidget()
        button1 = QtGui.QPushButton('Calendar', self)
        button1.setCheckable(True)
        button1.clicked[bool].connect(self.setWidget)
        button2 = QtGui.QPushButton('TextEdit', self)
        button2.setCheckable(True)
        button2.clicked[bool].connect(self.setWidget)
        splitter1 = QtGui.QSplitter(QtCore.Qt.Vertical)
        splitter1.addWidget(button1)
        splitter1.addWidget(button2)
        splitter1.addWidget(widget)
        hbox.addWidget(splitter1)
        self.setLayout(hbox)
        self.setGeometry(0, 0, 600, 600)
        self.setWindowTitle('Switching QWidgets')
        self.show()

    def setWidget(self, pressed):

        source = self.sender()

阅读 22

收藏
2024-12-05

共1个答案

小能豆

您必须使用QStackedWidget来更新索引。

class Example(QtGui.QWidget):
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)
        self.initUI()

    def initUI(self):
        hbox = QtGui.QHBoxLayout(self)
        self.stacked = QtGui.QStackedWidget(self)
        self.stacked.addWidget(QtGui.QCalendarWidget())
        self.stacked.addWidget(QtGui.QTextEdit())

        splitter1 = QtGui.QSplitter(QtCore.Qt.Vertical)

        for text in ["Calendar", "TextEdit"]:
            btn = QtGui.QPushButton(text, self)
            btn.clicked.connect(self.setWidget)
            splitter1.addWidget(btn)

        splitter1.addWidget(self.stacked)
        hbox.addWidget(splitter1)
        self.setLayout(hbox)
        self.setGeometry(0, 0, 600, 600)
        self.setWindowTitle('Switching QWidgets')
        self.show()

    def setWidget(self):
        source = self.sender()
        if source.text() == "Calendar":        
            self.stacked.setCurrentIndex(0)
        elif source.text() == "TextEdit":
            self.stacked.setCurrentIndex(1)   
2024-12-05