neo_v
neo_v

Reputation: 41

Trying to limit the QPushbuttons per row in PyQt4 GUI

i am adding 'n' number of pushbuttons into a QHBoxLayout. In a horizontal layout all the buttons arranged in a row and some go out of the screen. But i need only 7 buttons in a row. Is there a way?

class test(QtGui.QWidget):
  def __init__(self, parent=None):
      super(test, self).__init__(parent)
      self.test_btn = QtGui.QPushButton()
      self.test_btn.show()
      self.test_btn.clicked.connect(self.btn_fun)
      self.layout = QtGui.QHBoxLayout()
      self.setLayout(self.layout)

  def btn_fun(self):
      for i in range(42): 
         btns = QtGui.QPushButton('btns %d' %i)
         self.layout.addWidget(btns)
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = test()
    ex.show()
    sys.exit(app.exec_())

Upvotes: 0

Views: 51

Answers (1)

csunday95
csunday95

Reputation: 1319

In this case a QGridLayout is more appropriate. You can then specifically assign each button's row and column so that only a limited number is in each row.

class test(QtGui.QWidget):
    def __init__(self, parent=None):
        ...
        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)
        self.max_per_row = 7
        self.btn_fun()

    def btn_fun(self):
        for i in range(42):
            col = i % self.max_per_row
            row = i//self.max_per_row
            btns = QtGui.QPushButton('btns %d' % i)
            self.layout.addWidget(btns, row, col)

Upvotes: 2

Related Questions