6

这似乎是一件很简单的事情,但我似乎无法弄清楚。如何使按钮的最小宽度。它不断扩展到我放入的布局的宽度。在下面的示例中,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_())
4

2 回答 2

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_())
于 2014-03-11T03:13:04.517 回答
3

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

于 2013-01-19T22:03:51.527 回答