如何在 QTableWidget 中有垂直网格线?

How to have vertical grid lines in QTableWidget?

现在我正在使用 self.setShowGrid(False),但它完全删除了网格线。所以要么全有,要么全无。但我只想有垂直的网格线,而不是水平的,如图所示。

这可能吗?如何做到这一点?

一种可能的解决方案是使用委托绘制这些线条:

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