代码之家  ›  专栏  ›  技术社区  ›  AlgoRythm

PyQt5相当于WPF StackPanel

  •  1
  • AlgoRythm  · 技术社区  · 6 年前

    我正在使用PyQt5,希望将一些控件堆叠在彼此之上。我希望这些控件能够根据其内容确定自己的大小。例如,如果我有三个按钮,内容分别为“一”、“两个二”和“三个三”,那么第一个按钮应该是最小的,在左上角,第二个按钮应该在第一个按钮的正下方,稍微宽一点,依此类推。应该提到的是,这些将被放置在 QScrollArea ,您可以预期数百个堆叠的项目。

    我已经试过了 QVBoxLayout 但是,所有按钮都接收相同的大小,在屏幕上伸展,如果没有足够的填充,则在中间浮动。

    2 回复  |  直到 6 年前
        1
  •  1
  •   S. Nick    6 年前

    试试看:

    import sys
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class MyWin(QtWidgets.QWidget):
        def __init__(self, nameButton, parent=None):                        
            super().__init__()
    
            self.lay = QtWidgets.QGridLayout(self)
            self.lay.setContentsMargins(10, 10, 10, 10)
    
            for ind, itm in enumerate(nameButton):
                text = "{} {}".format(itm, itm*ind)
                self.button = QtWidgets.QPushButton(text)
                self.button.setFixedWidth(
                    QtGui.QFontMetrics(self.button.font()).width(self.button.text()+"___"))
                self.button.clicked.connect(self.onButton)
                self.lay.addWidget(self.button, ind, 0, QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
    
            self.lay.setRowStretch(ind+1, 1)
    
        def onButton(self):
            print(self.sender().text())
    
    
    nameButton = [' one', ' two ', ' three ']
    
    if __name__=="__main__":
        app = QtWidgets.QApplication(sys.argv)
        myapp = MyWin(nameButton)                                         
        myapp.show()
        sys.exit(app.exec_())
    

    enter image description here

        2
  •  1
  •   ekhumoro    6 年前

    您可以在中设置小部件的对齐方式 QVboxLayout

    当放置在滚动区域内时,它将如下所示:

    screenshot

    import sys
    from PyQt5 import QtCore, QtWidgets
    
    class Window(QtWidgets.QWidget):
        def __init__(self):
            super(Window, self).__init__()
            scroll = QtWidgets.QScrollArea()
            widget = QtWidgets.QWidget(scroll)
            vbox = QtWidgets.QVBoxLayout(widget)
            for index in range(5):
                for text in 'One', 'Two Two', 'Three Three Three':
                    button = QtWidgets.QToolButton()
                    button.setText('%s %s' % (text, index))
                    vbox.addWidget(button, 0, QtCore.Qt.AlignLeft)
            vbox.addStretch()
            scroll.setWidget(widget)
            layout = QtWidgets.QVBoxLayout(self)
            layout.addWidget(scroll)
    
    if __name__ == '__main__':
    
        app = QtWidgets.QApplication(sys.argv)
        window = Window()
        window.setGeometry(600, 100, 300, 300)
        window.show()
        sys.exit(app.exec_())