python-3.xpyside2qvboxlayout

PySide2 / QLayout: Cannot add a null layout to QHBoxLayout


I wanted to create with PySide2 a QHBoxLayout having 2 QVBoxLayout as child. For reading ease, I wanted to separate the 2 QVBoxLayout in different functions (left_panel and right_panel).

Please find below a sample of the script

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()

The problem is that when I execute the script I have the following error :

QLayout: Cannot add a null layout to QHBoxLayout

Do you know why and how I could correct that?

Thank you in advance.


Solution

  • The problem is simple: The right_panel method does not return anything or rather it returns None, so:

    mainLayout.addLayout(self.right_panel())
    

    is equivalent to Y:

    mainLayout.addLayout(None)
    

    The solution is to return 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