Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QListView show text when list is empty

Tags:

qt

qlistview

I want to show some text (like "No items") when there are no items in QListView.
I tried to override paintEvent method of QListView, but it doesn't have any effect.

like image 635
lightstep Avatar asked Dec 24 '13 18:12

lightstep


1 Answers

The code below shows a simple way of doing it by overloading the paintEvent method of the view. Painting of the text should probably use the style mechanism to obtain the font and pen/brush, but I'll leave that up for grabs by a keen editor.

It uses Qt 5 and its C++11 features, doing it the Qt 4 or pre-C++11 way would require a QObject-deriving class with a slot to connect to the spin box's valueChanged signal. The implementation of ListView doesn't need to change between Qt 4 and Qt 5.

screenshot

#include <QtWidgets>

class ListView : public QListView {
   void paintEvent(QPaintEvent *e) {
      QListView::paintEvent(e);
      if (model() && model()->rowCount(rootIndex()) > 0) return;
      // The view is empty.
      QPainter p(this->viewport());
      p.drawText(rect(), Qt::AlignCenter, "No Items");
   }
public:
   ListView(QWidget* parent = 0) : QListView(parent) {}
};

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   QWidget window;
   QFormLayout layout(&window);
   ListView view;
   QSpinBox spin;
   QStringListModel model;
   layout.addRow(&view);
   layout.addRow("Item Count", &spin);
   QObject::connect(&spin, (void (QSpinBox::*)(int))&QSpinBox::valueChanged,
                    [&](int value){
      QStringList list;
      for (int i = 0; i < value; ++i) list << QString("Item %1").arg(i);
      model.setStringList(list);
   });
   view.setModel(&model);
   window.show();
   return a.exec();
}
like image 108
Kuba hasn't forgotten Monica Avatar answered Sep 29 '22 08:09

Kuba hasn't forgotten Monica