小部件在GridLayout PySide2中彼此重叠

时间:2018-07-20 09:43:08

标签: python-3.x pyside2

我正在尝试使用GridLayout创建一个简单的程序,QWidget窗口内的所有小部件均会正确显示并缩放,但是LineEdit与标题Label重叠窗户的

from PySide2 import QtWidgets, QtCore, QtGui
import sys

class SimGrid(QtWidgets.QWidget):
    def __init__(self):
        super(SimGrid, self).__init__()
        self.setWindowTitle("My attempt at Grid Layout")
        grid = QtWidgets.QGridLayout()
        self.setLayout(grid)

        title = QtWidgets.QLabel("This is some big sample text to fill up")
        title.setAlignment(QtCore.Qt.AlignHCenter)
        text_edit = QtWidgets.QTextEdit()
        success = QtWidgets.QPushButton("Success", self)
        cancel = QtWidgets.QPushButton("Cancel", self)

        grid.addWidget(title, 0, 0, 0, 0)
        grid.addWidget(text_edit, 1, 0, 1, 2)
        grid.addWidget(success, 4, 0)
        grid.addWidget(cancel, 4, 1)
        self.show()

1 个答案:

答案 0 :(得分:1)

根据docs,您使用的是以下方法:

  

void QGridLayout :: addWidget(QWidget * widget,int fromRow,int   fromColumn,int rowSpan,int columnSpan,Qt :: Alignment对齐=   ...)

第三个和第四个参数分别指示将要占用的数量和列,在您的情况下,标题将占用0行和0列,这是不正确的。

使用这些条件,您需要的是以下内容:

import sys
from PySide2 import QtWidgets, QtCore, QtGui


class SimGrid(QtWidgets.QWidget):
    def __init__(self):
        super(SimGrid, self).__init__()
        self.setWindowTitle("My attempt at Grid Layout")
        grid = QtWidgets.QGridLayout()
        self.setLayout(grid)

        title = QtWidgets.QLabel("This is some big sample text to fill up")
        title.setAlignment(QtCore.Qt.AlignHCenter)
        text_edit = QtWidgets.QTextEdit()
        success = QtWidgets.QPushButton("Success", self)
        cancel = QtWidgets.QPushButton("Cancel", self)

        grid.addWidget(title, 0, 0, 1, 2)
        grid.addWidget(text_edit, 1, 0, 1, 2)
        grid.addWidget(success,2, 0, 1, 1)
        grid.addWidget(cancel,  2, 1, 1, 1)
        self.show()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = SimGrid()
    w.show()
    sys.exit(app.exec_())

enter image description here