QListView在列表为空时显示文本 [英] QListView show text when list is empty
问题描述
当QListView中没有项目时,我想显示一些文本(例如无项目").
我试图重写QListView的paintEvent方法,但没有任何效果.
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.
推荐答案
以下代码通过重载视图的paintEvent
方法显示了一种简单的方法.绘制文本可能应该使用样式机制来获取字体和笔/画笔,但我将留给敏锐的编辑者来解决.
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.
它使用Qt 5及其C ++ 11功能,以Qt 4或C ++ 11之前的方式进行操作将需要带有插槽的QObject派生类,以连接到旋转框的valueChanged
信号. ListView
的实现无需在Qt 4和Qt 5之间进行更改.
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();
}
这篇关于QListView在列表为空时显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!