【问题标题】:How do I set layout's fixed height in PyQt5?如何在 PyQt5 中设置布局的固定高度?
【发布时间】:2018-09-23 09:15:15
【问题描述】:

我正在尝试为QHBoxLayout 设置一个固定高度。为了详细说明这一点,我需要为我的水平布局设置一个特定的高度。但是,我找不到这样做的正确方法。我应该怎么做才能做到这一点?

hbox1 = QHBoxLayout()

【问题讨论】:

  • 布局没有明确的高度或宽度,只有小部件有。

标签: python python-3.x pyqt pyqt5 qlayout


【解决方案1】:

正如@ekhumuro 在 QHBoxLayout 中所指出的,您无法设置固定高度,您必须对将包含它的小部件执行此操作,如下所示:

import random
from PyQt5 import QtCore, QtGui, QtWidgets


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.setFixedHeight(300)

        lay = QtWidgets.QHBoxLayout(self)

        for letter in "ABCDEFG":
            label = QtWidgets.QLabel(letter, alignment=QtCore.Qt.AlignCenter)
            color = QtGui.QColor(*[random.randint(0, 255) for _ in range(3)])
            label.setStyleSheet("background-color: {}".format(color.name()))
            lay.addWidget(label)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多