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

标签 c++ qt qtstylesheets

我想在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;
}
  • 在 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/

    相关文章:

    c++ - Qt:一旦显示,如何将光标焦点转移到“查找”对话框/工具中的字段?

    c++ - 类中的数组未经初始化

    c++ - 使用常量内存使用的 xml 解析

    python - 如何删除QTreeWidgetItem

    qt - 在 qt StyleSheets 中使用变量

    c++ - Qt Stylesheet按钮背景颜色

    c++ - 当 C++ mex 文件完成并将数据传回 MATLAB 时是否有开销?

    c++ - Qt 读取 XML 文件

    linux - 制作失败 : make: *** [sub-corelib-install_subtargets-ordered] Error 2

    c++ - 如何在运行时更改 styleSheet 属性?