QtableView placeholder text before table appears

584 Views Asked by At

I have a very simple QtableView like which is populated after the program runs. The program takes a few seconds before it populates the table like so..

enter image description here

I am wondering how to enable a placeholder text "No data" on the QTableView before the program runs like so...

enter image description here

1

There are 1 best solutions below

1
On BEST ANSWER

You must override the paintEvent method where you check if there is no model or the model has no rows then paint the placeholder text:

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