Increase Height of QPushButton in PyQT

a 夏天 提交于 2020-08-02 08:16:34

问题


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)


来源:https://stackoverflow.com/questions/45100018/increase-height-of-qpushbutton-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!