将QPushButton宽度缩小到最小

时间:2013-01-19 20:10:20

标签: qt pyqt qpushbutton

这看起来很简单,但我似乎无法弄明白。如何使按钮达到最小宽度。它不断扩展到我放入的布局的宽度。在下面的例子中,QPushButton宽度最终与QLabel相同:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class MyWindow(QWidget):

    def __init__(self,parent = None):

        QWidget.__init__(self,parent)

        layout = QVBoxLayout()
        layout.addWidget(QLabel('this is a really, really long label that goes on and on'))
        layout.addWidget(QPushButton('short button'))

        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

2 个答案:

答案 0 :(得分:9)

setMaximumWidth适合我

from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QtGui.QHBoxLayout()
        texts = [":)",
                 "&Short",
                 "&Longer",
                 "&Different && text",
                 "More && text",
                 "Even longer button text", ]
        for text in texts:
            btn = QtGui.QPushButton(text)
            double = text.count('&&')
            text = text.replace('&', '') + ('&' * double)
            width = btn.fontMetrics().boundingRect(text).width() + 7
            btn.setMaximumWidth(width)
            layout.addWidget(btn)
        self.setLayout(layout)

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)
    mainWin = Window()
    mainWin.show()
    sys.exit(app.exec_())

答案 1 :(得分:2)

请参阅http://qt-project.org/doc/qt-4.8/qwidget.html#sizePolicy-prophttp://qt-project.org/doc/qt-4.8/qsizepolicy.html#Policy-enum,了解如何在动态布局中控制小部件大小调整。

如果单独更改SizePolicy(你应该)没有得到满意的结果,你也可以看看这些好人:http://qt-project.org/doc/qt-4.8/qspaceritem.html