如何修改嵌套 PyQt 布局中的间距?

问题描述 投票:0回答:2

目前,我在 QHBoxLayout 的第一列中有一个嵌套的 QVBoxLayout,但无论我对

.setContentMargins
.setSpacing
进行更改,第一列中都没有任何变化。

import sys
import io
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        # Main widget/window
        self.setWindowTitle('Test')
        self.window_width, self.window_height = 1600, 900
        self.setMinimumSize(self.window_width, self.window_height)

        layout = QHBoxLayout()
        self.setLayout(layout)

        leftside = QWidget()
        leftlayout = QVBoxLayout()

        # Creating textbox and adding to leftside GUI
        lineEdit = QLineEdit()
        leftlayout.addWidget(lineEdit)
        leftlayout.addWidget(QPushButton('Placeholder'))
        leftside.setLayout(leftlayout)

        # Adding both widgets to main layout
        testWidget = QWidget()
        testWidget.setStyleSheet("background-color: blue")
        layout.addWidget(leftside, 2)
        layout.addWidget(testWidget, 8)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet('''
        QWidget {
            font-size: 20px;
        }
    ''')

    myApp = MyApp()
    myApp.show()

    try:
        sys.exit(app.exec_())
    except SystemExit:
        print('Closing Window...')

给我留下这样的结果: Current result

我想要的: enter image description here

python pyqt pyqt5
2个回答
2
投票

使用

addStretch()
方法:

class MyApp(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Test")
        self.window_width, self.window_height = 1600, 900
        self.setMinimumSize(self.window_width, self.window_height)

        leftside = QWidget()
        leftlayout = QVBoxLayout(leftside)
        lineEdit = QLineEdit()
        leftlayout.addWidget(lineEdit)
        leftlayout.addWidget(QPushButton("Placeholder"))
        leftlayout.addStretch()

        testWidget = QWidget()
        testWidget.setStyleSheet("background-color: blue")

        layout = QHBoxLayout(self)
        layout.addWidget(leftside)
        layout.addWidget(testWidget, stretch=1)

0
投票

您可以使用垂直垫片。 由于您的左侧是垂直布局,因此只需在前 2 个小部件之后添加垂直间隔即可。

vertical_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum,QSizePolicy.Expanding)

leftlayout.addWidget(lineEdit)
leftlayout.addWidget(QPushButton('Placeholder'))
leftlayout.addItem(vertical_spacer)
leftside.setLayout(leftlayout)
© www.soinside.com 2019 - 2024. All rights reserved.