Qtable在 table 出现之前查看占位符文本

QtableView placeholder text before table appears

我有一个非常简单的 QtableView,它是在程序运行后填充的。该程序需要几秒钟才能像这样填充 table..

我想知道如何在程序运行之前在 QTableView 上启用占位符文本“无数据”...

您必须覆盖 paintEvent 方法,在该方法中检查是否没有模型或模型是否没有行,然后绘制占位符文本:

from PySide2 import QtCore, QtGui, QtWidgets


class TableView(QtWidgets.QTableView):
    def paintEvent(self, event):
        super().paintEvent(event)
        if self.model() is not None and self.model().rowCount() > 0:
            return
        painter = QtGui.QPainter(self.viewport())
        painter.save()
        col = self.palette().placeholderText().color()
        painter.setPen(col)
        fm = self.fontMetrics()
        elided_text = fm.elidedText(
            "No data", QtCore.Qt.ElideRight, self.viewport().width()
        )
        painter.drawText(self.viewport().rect(), QtCore.Qt.AlignCenter, elided_text)
        painter.restore()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = TableView()
    model = QtGui.QStandardItemModel(0, 3)
    w.setModel(model)
    w.resize(640, 480)
    w.show()

    def on_timeout():
        if model.rowCount() > 0:
            model.setRowCount(0)
        else:
            for j in range(4):
                items = [
                    QtGui.QStandardItem(f"item ({j}-{i})")
                    for i in range(model.columnCount())
                ]
                model.appendRow(items)

    timer = QtCore.QTimer(interval=1000, timeout=on_timeout)
    timer.start()

    sys.exit(app.exec_())