QListView show text when list is empty

后端 未结 2 865
[愿得一人]
[愿得一人] 2021-01-18 17:38

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.

相关标签:
2条回答
  • 2021-01-18 17:42

    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();
    }
    
    0 讨论(0)
  • 2021-01-18 17:59

    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.

    0 讨论(0)
提交回复
热议问题