gpt4 book ai didi

c++ - 如何设置QListWidget的第一项/最后一项的样式?

转载 作者:行者123 更新时间:2023-11-30 04:56:54 25 4
gpt4 key购买 nike

我想在QListWidget中实现以下效果:

enter image description here

不幸的是,QListWidget 的样式表中没有QListWidget::item:first

qss中有没有css的兄弟选择器li~li

我检查了 Qt Style example ,但那里的信息对我来说还不够。

最佳答案

原因

QListView,响应。 QListWidget 确实不支持 ::item:first,因此您无法使用样式表实现您想要的。

解决方案

您可以改用委托(delegate)。子类 QStyledItemDelegate , 重新实现 QAbstractItemDelegate::paintQAbstractItemDelegate::sizeHint并根据您的喜好进行调整。

例子

以下是如何实现此解决方案的示例:

  1. 创建一个类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;
}
  1. 在 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);
}

结果

提供的示例产生以下结果:

Window with QListWidget containing 6 items separated by a line

关于c++ - 如何设置QListWidget的第一项/最后一项的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52292184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com