我正在尝试设置类似于此问题的布局。 Create Qt layout with fixed height。我正在尝试使用此处发布的解决方案,但似乎无法在python中重新创建它。如何创建具有水平框布局的小部件并设置新小部件的尺寸?当我尝试在python中重新创建代码时,我的窗口小部件最终以布局而不是窗口小部件的形式出现。下面是我想用python重写的代码,在此先感谢:

// first create the four widgets at the top left,
// and use QWidget::setFixedWidth() on each of them.

// then set up the top widget (composed of the four smaller widgets):
QWidget *topWidget = new QWidget;
QHBoxLayout *topWidgetLayout = new QHBoxLayout(topWidget);
topWidgetLayout->addWidget(widget1);
topWidgetLayout->addWidget(widget2);
topWidgetLayout->addWidget(widget3);
topWidgetLayout->addWidget(widget4);
topWidgetLayout->addStretch(1); // add the stretch
topWidget->setFixedHeight(50);

// now put the bottom (centered) widget into its own QHBoxLayout
QHBoxLayout *hLayout = new QHBoxLayout;
hLayout->addStretch(1);
hLayout->addWidget(bottomWidget);
hLayout->addStretch(1);
bottomWidget->setFixedSize(QSize(50, 50));

// now use a QVBoxLayout to lay everything out
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(topWidget);
mainLayout->addStretch(1);
mainLayout->addLayout(hLayout);
mainLayout->addStretch(1);

最佳答案

从C ++到Python的翻译没有太多的科学知识,因为您只需要了解逻辑即可:

from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QApplication, QComboBox, QHBoxLayout, QLineEdit, QPushButton, QSpinBox, QToolButton, QVBoxLayout, QWidget


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

        widget1 = QPushButton("widget1")
        widget2 = QSpinBox()
        widget3 = QComboBox()
        widget4 = QLineEdit()

        bottomWidget = QToolButton(text="botton")
        # first create the four widgets at the top left,
        # and use QWidget::setFixedWidth() on each of them.

        # then set up the top widget (composed of the four smaller widgets):

        topWidget = QWidget()
        topWidgetLayout = QHBoxLayout(topWidget)
        topWidgetLayout.addWidget(widget1)
        topWidgetLayout.addWidget(widget2)
        topWidgetLayout.addWidget(widget3)
        topWidgetLayout.addWidget(widget4)
        topWidgetLayout.addStretch(1)
        topWidget.setFixedHeight(50)

        # now put the bottom (centered) widget into its own QHBoxLayout
        hLayout = QHBoxLayout()
        hLayout.addStretch(1)
        hLayout.addWidget(bottomWidget)
        hLayout.addStretch(1)
        bottomWidget.setFixedSize(QSize(50, 50))

        # now use a QVBoxLayout to lay everything out
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(topWidget)
        mainLayout.addStretch(1)
        mainLayout.addLayout(hLayout)
        mainLayout.addStretch(1)

        self.setLayout(mainLayout)
        self.resize(640, 480)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)

    w = Widget()
    w.show()
    sys.exit(app.exec_())


python - 如何控制布局尺寸PyQt5-LMLPHP

关于python - 如何控制布局尺寸PyQt5,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57679247/

10-14 11:48
查看更多