Search code examples
pythonpysidepyside2

Add multiple columns inside a tableview cell


Click here to see the picture

I'm trying to create a table that have a column inside a cell. Is there an easy way to implement this design to the table view I'm working with?

This is my code right now:

class ColumnsLayout(QWidget):
    def __init__(self, parent=None):
        super(ColumnsLayout, self).__init__(parent)
        table_row = QTableWidget()
        table_row.setColumnCount(3)
        table_row.horizontalHeader().setVisible(False)
        for x in range(0, 3):
            table_row.horizontalHeader().setSectionResizeMode(x, QHeaderView.Stretch)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(table_row)
        self.setLayout(layout)
self.ui.fields_tableWidget.setCellWidget(self.current_default_total_row, 2, ColumnsLayout())

Solution

  • You can use setSpan() to join cells

    from PySide2 import QtWidgets
    
    class ColumnsLayout(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(ColumnsLayout, self).__init__(parent)
            table_row = QtWidgets.QTableWidget(4, 3)
            table_row.horizontalHeader().hide()
            table_row.setSpan(0, 0, 1, 3)
            for x in range(0, 3):
                table_row.horizontalHeader().setSectionResizeMode(x, QtWidgets.QHeaderView.Stretch)
            layout = QtWidgets.QHBoxLayout(self)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.setSpacing(0)
            layout.addWidget(table_row)
    
    if __name__ == '__main__':
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = ColumnsLayout()
        w.show()
        sys.exit(app.exec_())
    

    enter image description here