QListView show text when list is empty

最后都变了- 提交于 2019-12-01 19:09:27

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.

#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();
}

If you use a QListView, you probably have a custom model containing data you want to display. This is maybe the best place to returns "No items" when your model is empty.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!