Creating a custom widget in PyQT5

后端 未结 2 1661
谎友^
谎友^ 2020-12-15 13:58

I would like to know how one can create a custom widget in pyqt. I\'ve seen many different examples for C++, and a couple non descript examples for pyqt, but nothing that re

2条回答
  •  时光取名叫无心
    2020-12-15 14:10

    In the following it is shown how to implement a QStackedWidget with 2 buttons, the basic idea is to layout the design, for this we analyze that a QVBoxLayout must be placed to place the QStackedWidget and another layout, this second layout will be a QHBoxLayout to have the buttons. Then we connect the signals that handle the transition between pages. Also in this example I have created 3 types of widgets that will be placed on each page.

    from PyQt5.QtWidgets import *
    
    
    class Widget1(QWidget):
        def __init__(self, parent=None):
            QWidget.__init__(self, parent=parent)
            lay = QVBoxLayout(self)
            for i in range(4):
                lay.addWidget(QPushButton("{}".format(i)))
    
    class Widget2(QWidget):
        def __init__(self, parent=None):
            QWidget.__init__(self, parent=parent)
            lay = QVBoxLayout(self)
            for i in range(4):
                lay.addWidget(QLineEdit("{}".format(i)))
    
    class Widget3(QWidget):
        def __init__(self, parent=None):
            QWidget.__init__(self, parent=parent)
            lay = QVBoxLayout(self)
            for i in range(4):
                lay.addWidget(QRadioButton("{}".format(i)))
    
    class stackedExample(QWidget):
        def __init__(self, parent=None):
            QWidget.__init__(self, parent=parent)
            lay = QVBoxLayout(self)
            self.Stack = QStackedWidget()
            self.Stack.addWidget(Widget1())
            self.Stack.addWidget(Widget2())
            self.Stack.addWidget(Widget3())
    
            btnNext = QPushButton("Next")
            btnNext.clicked.connect(self.onNext)
            btnPrevious = QPushButton("Previous")
            btnPrevious.clicked.connect(self.onPrevious)
            btnLayout = QHBoxLayout()
            btnLayout.addWidget(btnPrevious)
            btnLayout.addWidget(btnNext)
    
            lay.addWidget(self.Stack)
            lay.addLayout(btnLayout)
    
        def onNext(self):
            self.Stack.setCurrentIndex((self.Stack.currentIndex()+1) % 3)
    
        def onPrevious(self):
            self.Stack.setCurrentIndex((self.Stack.currentIndex()-1) % 3)
    
    
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        w = stackedExample()
        w.show()
        sys.exit(app.exec_())
    

提交回复
热议问题