如何设置QListWidget的first/last项的样式?
How to set the style of the first/last item of QListWidget?
我想在QListWidget中实现如下效果:
很遗憾,QListWidget的样式表中没有QListWidget::item:first
。
在qss
中有没有类似css
的兄弟选择器li~li
的东西?
我已经检查了 Qt Style example,但是那里的信息对我来说还不够。
查看 Style Reference 以了解小部件特定样式的概述。
原因
QListView,相应。 QListWidget确实不支持::item:first
,所以你无法通过使用样式表来实现你想要的。
解决方案
您可以改用委托。 Subclass QStyledItemDelegate, reimplement QAbstractItemDelegate::paint and QAbstractItemDelegate::sizeHint 并根据您的喜好调整它们。
例子
以下是如何实施此解决方案的示例:
- 创建 class
Delegate : public QStyledItemDelegate
在Delegate.cpp:
void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
int b = option.rect.bottom() - 1;
painter->save();
painter->setClipping(true);
painter->setClipRect(option.rect);
if (index.row() < index.model()->rowCount() - 1)
painter->drawLine(option.rect.left() + 5, b, option.rect.right() - 5, b);
painter->restore();
QStyledItemDelegate::paint(painter, option, index);
}
QSize Delegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize sz(QStyledItemDelegate::sizeHint(option, index));
sz.setHeight(32);
return sz;
}
- 在 Qt 小部件应用程序中测试 class
在MainWindow.cpp:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
auto *list = new QListWidget(this);
list->addItems(QStringList{"1", "2", "3", "4", "5", "6"});
list->setItemDelegate(new Delegate(this));
list->setFrameStyle(QFrame::NoFrame);
setCentralWidget(list);
setContentsMargins(9, 9, 9, 9);
resize(200, 300);
}
结果
提供的示例产生以下结果:
我想在QListWidget中实现如下效果:
很遗憾,QListWidget的样式表中没有QListWidget::item:first
。
在qss
中有没有类似css
的兄弟选择器li~li
的东西?
我已经检查了 Qt Style example,但是那里的信息对我来说还不够。
查看 Style Reference 以了解小部件特定样式的概述。
原因
QListView,相应。 QListWidget确实不支持::item:first
,所以你无法通过使用样式表来实现你想要的。
解决方案
您可以改用委托。 Subclass QStyledItemDelegate, reimplement QAbstractItemDelegate::paint and QAbstractItemDelegate::sizeHint 并根据您的喜好调整它们。
例子
以下是如何实施此解决方案的示例:
- 创建 class
Delegate : public QStyledItemDelegate
在Delegate.cpp:
void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
int b = option.rect.bottom() - 1;
painter->save();
painter->setClipping(true);
painter->setClipRect(option.rect);
if (index.row() < index.model()->rowCount() - 1)
painter->drawLine(option.rect.left() + 5, b, option.rect.right() - 5, b);
painter->restore();
QStyledItemDelegate::paint(painter, option, index);
}
QSize Delegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize sz(QStyledItemDelegate::sizeHint(option, index));
sz.setHeight(32);
return sz;
}
- 在 Qt 小部件应用程序中测试 class
在MainWindow.cpp:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
auto *list = new QListWidget(this);
list->addItems(QStringList{"1", "2", "3", "4", "5", "6"});
list->setItemDelegate(new Delegate(this));
list->setFrameStyle(QFrame::NoFrame);
setCentralWidget(list);
setContentsMargins(9, 9, 9, 9);
resize(200, 300);
}
结果
提供的示例产生以下结果: