Search code examples
pythonpython-2.7mayapyside2qtablewidget

How to have vertical grid lines in QTableWidget?


Right now I am using self.setShowGrid(False), but it completely removes the grid lines. So it's either all or nothing. But I want to have only vertical grid lines, not horizontal, like in the picture.

Is this possible? How to do this?

enter image description here


Solution

  • One possible solution is to paint those lines using a delegate:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class VerticalLineDelegate(QtWidgets.QStyledItemDelegate):
        def paint(self, painter, option, index):
            super(VerticalLineDelegate, self).paint(painter, option, index)
            line = QtCore.QLine(option.rect.topRight(), option.rect.bottomRight())
            color = option.palette.color(QtGui.QPalette.Mid)
            painter.save()
            painter.setPen(QtGui.QPen(color))
            painter.drawLine(line)
            painter.restore()
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = QtWidgets.QTableWidget(10, 4)
        delegate = VerticalLineDelegate(w)
        w.setItemDelegate(delegate)
        w.setShowGrid(False)
        w.resize(640, 480)
        w.show()
        sys.exit(app.exec_())
    

    enter image description here