List placeholder
Unsolved
General and Desktop
-
So, I wanted to implemented a placeholder text for a list (QListView) which would be displayed if the list has no items.
Currently I'm doing it using QStackedLayout but it requires quite a bit of boilerplate. You need to create a wrapper QWidget that will hold QStackedLayout, and also another wrapper QWidget for placeholder text so it can be centered:
auto stackedLayoutWrapper = new QWidget(parent); auto stackedLayout = new QStackedLayout(stackedLayoutWrapper); stackedLayout->addWidget(listView); auto placeholderWrapper = new QWidget(); auto placeholderLayout = new QVBoxLayout(placeholderWrapper); auto placeholder = new QLabel("No items"); placeholderLayout->addItem(placeholder, 0, Qt::AlignCenter); stackedLayout->addWidget(placeholderWrapper);
And then I discovered another neat way to do it, using QListView::viewport():
auto placeholderLayout = new QVBoxLayout(listView->viewport()); auto placeholder = new QLabel("No items"); placeholderLayout->addWidget(placeholder, 0, Qt::AlignCenter);
This works right now, but question is, how safe is it set a layout on the viewport() like this?
-
@equeim
viewport()
is a documented API, so it's not an implementation detail, but you're doing a lot of work that is not really needed.
You can simply subclass the listview and draw the text there, e.g.void MyListView::paintEvent(QPaintEvent* evt) { QListView::paintEvent(evt); if (!model() || model()->rowCount() == 0) { QPainter p(viewport()); p.drawText(rect(), Qt::AlignCenter, "No items"); } }
1/4