سؤال

I want to show an item "There are no elements in this view" if the connected QTreeView model (set by QSortFilterProxyModel) has no elements to show.

How can I implement such things?

Thanks for small hints.

هل كانت مفيدة؟

المحلول

One of the solution is overriding the tree view's paint event and draw the custom text when there is no items in the view. You need to sub class the QTreeView in the following way:

class TreeView : public QTreeView
{
[..]
protected:
    void paintEvent(QPaintEvent * event)
    {
        if (model() && model()->rowCount() > 0) {
            QTreeView::paintEvent(event);
        } else {
            // If no items draw a text in the center of the viewport.
            QPainter painter(viewport());
            QString text(tr("There are no elements in this view"));
            QRect textRect = painter.fontMetrics().boundingRect(text);
            textRect.moveCenter(viewport()->rect().center());
            painter.drawText(textRect, Qt::AlignCenter, text);      
        }
    }
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top