Increase Height of QPushButton in PyQT

2020-07-14 00:54发布

问题:

I have 2 QPushButton in the app window: btn1 needs to be 5x the height of btn2.

Problem: Tried setting the row span of self.btn1 to 5 using layout.addWidget but the height remains unchanged. did I miss out on a setting?

import sys
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()

    def initUI(self):
        layout = QtGui.QGridLayout()

        self.btn1 = QtGui.QPushButton('Hello')
        self.btn2 = QtGui.QPushButton('World')

        layout.addWidget(self.btn1, 1, 1, 5, 1)
        layout.addWidget(self.btn2, 6, 1, 1, 1)

        centralWidget = QtGui.QWidget()
        centralWidget.setLayout(layout)
        self.setCentralWidget(centralWidget)

def main():
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

回答1:

You'll need to change the buttons' size policy:

self.btn1.setSizePolicy(
    QtGui.QSizePolicy.Preferred,
    QtGui.QSizePolicy.Expanding)

self.btn2.setSizePolicy(
    QtGui.QSizePolicy.Preferred,
    QtGui.QSizePolicy.Preferred)

From Qt doc, by default:

Button-like widgets set the size policy to specify that they may stretch horizontally, but are fixed vertically.

i.e. The default size policy of QPushButton is Minimum horizontally, and Fixed vertically.

In addition, a simpler way to achieve what you want in the example is to use a QVBoxLayout, and set the stretch factor when calling addWidget(). i.e.

def initUI(self):
    layout = QtGui.QVBoxLayout()

    self.btn1 = QtGui.QPushButton('Hello')
    self.btn2 = QtGui.QPushButton('World')

    self.btn1.setSizePolicy(
        QtGui.QSizePolicy.Preferred,
        QtGui.QSizePolicy.Expanding)

    self.btn2.setSizePolicy(
        QtGui.QSizePolicy.Preferred,
        QtGui.QSizePolicy.Preferred)

    layout.addWidget(self.btn1, 5)
    layout.addWidget(self.btn2, 1)

    centralWidget = QtGui.QWidget()
    centralWidget.setLayout(layout)
    self.setCentralWidget(centralWidget)