我想在QListWidget中实现以下效果:
不幸的是,QListWidget的样式表中没有QListWidget::item:first
。
qss
中是否有类似于 css
的兄弟选择器 li~li
的东西?
我已经检查了 Qt Style example ,但那里的信息对我来说还不够。
最佳答案
原因
QListView,分别。 QListWidget确实不支持::item:first
,所以你无法通过使用样式表来实现你想要的。
解决方案
您可以使用委托(delegate)。子类QStyledItemDelegate ,重新实现QAbstractItemDelegate::paint和 QAbstractItemDelegate::sizeHint并根据您的喜好调整它们。
示例
以下是如何实现此解决方案的示例:
- 创建一个类
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 小部件应用程序中测试该类
在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);
}
结果
提供的示例产生以下结果:
关于c++ - 如何设置QListWidget第一个/最后一个项目的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52292184/