在QGridLayout中放置小部件

时间:2012-10-26 03:30:23

标签: qt pyqt grid-layout

我需要在QWidget中创建QtoolButtonQgridLayout)而不指定行和列的索引。它应该根据提到的行和列自动创建到布局中的下一个空单元格。

我无法在QgridLayout帮助中找到任何方法。

我尝试了.addWidget (self, QWidget w),但它将所有QWidget添加到(0,0)的索引中,并且所有按钮都相互叠加。

提前致谢。

3 个答案:

答案 0 :(得分:2)

假设您有一个包含4行和3列的QGridLayout,并且您想要从上到下和从左到右自动添加按钮。如果您能够预测要添加的下一个按钮的位置,则可以轻松实现。在我们的案例中:

  • row =添加的按钮数/列数
  • 列=添加按钮的数量%列数

(类似的其他类型的填充工作)。我们把它放在代码中:

from PyQt4.QtGui import *

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.central = QWidget(self)
        self.grid = QGridLayout(self.central)
        self.rows = 4
        self.cols = 3
        self.items = self.grid.count()
        while(self.items < (self.rows * self.cols)):
            self.addButton()
        self.setCentralWidget(self.central)

    def addButton(self):
        # the next free position depends on the number of added items
        row = self.items/self.cols
        col = self.items % self.cols
        # add the button to the next free position
        button = QPushButton("%s, %s" % (row, col))
        self.grid.addWidget(button, row, col)
        # update the number of items
        self.items = self.grid.count()

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = MyMainWindow()
    ui.show()
    sys.exit(app.exec_())

答案 1 :(得分:1)

您可以通过自己计算行和列来处理“下一个空单元格”。例如,您可以根据需要将QGridLayout子类化为实现任何“下一个空单元”算法:

class AutoGridLayout(QGridLayout):
    def __init__(self):
        QGridLayout.__init__(self)
        self.column = 0
        self.row = 0

    def addNextWidget(self, widget):
        self.addWidget(widget, self.row, self.column)
        self.column = self.column + 1   # Automatically advance to next column

# Setup main widget
app = QApplication(sys.argv)
mainWindow = QMainWindow()
centralWidget = QWidget()
mainWindow.setCentralWidget(centralWidget)

# Add widgets using the AutoGridLayout
layout = AutoGridLayout()
centralWidget.setLayout(layout)
layout.addNextWidget(QPushButton("1", centralWidget))
layout.addNextWidget(QPushButton("2", centralWidget))
layout.addNextWidget(QPushButton("3", centralWidget))

# Show and run the application
mainWindow.show()
app.exec_()

此来源仅显示一般概念 - 您可以根据需要管理行和列索引。只需通过计算下一个所需的行/列(在本例中,使用第0行中的下一列),在addNextWidget()方法中实现必要的逻辑。

答案 2 :(得分:1)

除了其他答案之外:如果您只需要具有可变数量的项目的行,而不是实际的网格,那么您应该使用嵌套在一个QVBoxLayout中的多个QHBoxLayouts(每行一个)。这也将为您提供您想要的行为,按需创建新项目,没有令人讨厌的差距。