PySide2 / QLayout:无法将空布局添加到QHBoxLayout

问题描述

我想用pyside2创建一个以2个QVBoxLayout作为子元素的QHBoxLayout。 为了便于阅读,我想将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

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

谢谢。

解决方法

问题很简单: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