Qt: QListWidget dividing line after elements of an object?

Is this related to Qt: QListWidget line separator between elements? But this answer above adds a separator line after each element, I would like to know how to add a separator line after certain elements.

+4
source share
3 answers

Create QListWidgetItemrepresenting a delimiter. Such an element should have been determined setSizeHint(), therefore, its height is small, and setFlags()should also be determined Qt::NoItemFlags, therefore, the element is not selected, etc. Then, adding the element to QListWidget, put a QFramewith its shape set to QFrame::HLine, as the widget of the element (using QListWidget::setItemWidget()).

Regarding your additional question from the comment which:

I want to add some space on each side of this line / border separator. How can I achieve this?

, , - QFrame QWidget QWidget (, QWidget -). : QWidget::setContentsMargins(int left, int top, int right, int bottom)

+5

: p , QStyledItemDelegate, :

void MyStyledItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter, option, index);

    // I have decided to use Qt::UserRole + 1 to store my boolean
    // but it could be any other role while it value is bigger than Qt::UserRole
    QVariant isSeparator = index.data(Qt::UserRole + 1);
    if (isSeparator.isValid() && isSeparator.toBool())
    {
        QRect rct = option.rect;
        rct.setY(rct.bottom() - 1);
        painter->fillRect(rct, QColor::fromRgb(qRgb(0, 0, 0)));
    }
}

QListWidgetItem :

// Qt::UserRole + 1 => Must match the role set in the delegate
item->setData(Qt::UserRole + 1, true);

QListWidget

listWidget->setItemDelegate(new MyStyledItemDelegate());

, Qt:: UserRole + 1 true.

+1

.

myListWidget->setStyleSheet( "QListWidget::item[separator="true"] { border-bottom: 1px solid black; }" );

, :

myWidget->setProperty("separator", true);

: :

Warning. If the value of the Qt property changes after the stylesheet has been configured, it may be necessary to force the recompilation of the stylesheet. One way to achieve this is to undo the stylesheet and set it again.

-1
source

Source: https://habr.com/ru/post/1547874/


All Articles