首页 > 解决方案 > PySide2 / QLayout:无法向 QHBoxLayout 添加空布局

问题描述

我想用 PySide2 创建一个 QHBoxLayout,它有 2 个 QVBoxLayout 作为子级。为了便于阅读,我想将 2 个 QVBoxLayout 分隔为不同的功能(left_panel 和 right_panel)。

请在下面找到脚本示例

import sys
from PySide2 import QtCore, QtGui
from PySide2.QtWidgets import (QVBoxLayout, QTableWidget, QWidget, QLabel, QLineEdit, QPushButton, QCheckBox,
                             QTextEdit, QGridLayout, QApplication, QAbstractItemView, QHBoxLayout)

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        mainLayout = QHBoxLayout()

        mainLayout.addLayout(self.left_panel())
        mainLayout.addLayout(self.right_panel())
        self.setLayout(mainLayout)

    def right_panel(self):
        rightLayout = QVBoxLayout()

        self.tableCert = QTableWidget()
        self.tableCert.setColumnCount(3)
        self.tableCertColumnLabels = ["First Name","Surname","login"]
        self.tableCert.setRowCount(2)
        self.tableCert.setHorizontalHeaderLabels(self.tableCertColumnLabels)
        self.tableCert.verticalHeader().setVisible(False)
        self.tableCert.horizontalHeader().setVisible(True)     
        rightLayout.addWidget(self.tableCert)
    
    def left_panel(self):
        pass #Here we will have the content of the other QVBoxLayout

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

问题是当我执行脚本时出现以下错误:

QLayout: Cannot add a null layout to QHBoxLayout

你知道为什么以及如何纠正吗?

先感谢您。

标签: python-3.xpyside2qvboxlayout

解决方案


问题很简单:该right_panel方法不返回任何内容,或者返回 None,因此:

mainLayout.addLayout(self.right_panel())

相当于 Y:

mainLayout.addLayout(None)

解决办法是返回rightLayout:

def right_panel(self):
    rightLayout = QVBoxLayout()

    self.tableCert = QTableWidget()
    self.tableCert.setColumnCount(3)
    self.tableCertColumnLabels = ["First Name", "Surname", "login"]
    self.tableCert.setRowCount(2)
    self.tableCert.setHorizontalHeaderLabels(self.tableCertColumnLabels)
    self.tableCert.verticalHeader().setVisible(False)
    self.tableCert.horizontalHeader().setVisible(True)
    rightLayout.addWidget(self.tableCert)
    return rightLayout

推荐阅读