Accessing object-specific stylesheet in custom delegate



  • How do I access an object's custom stylesheet from within a custom delegate that's drawing for that object? My specific situation is:

    • I have a QListView. I customized the display of its items by defining a custom stylesheet in Designer. Among other things, I set QListView::item{padding: 5px};

    • I created a custom delegate in code (derived from QStyledItemDelegate) and passed it to my QListView object.

    Now within my delegate's paint() I don't know how to access the stylesheet I defined in Designer. Specifically I'd like to get the content rect that takes into account the item padding I defined - although I'd also like to know generally how to access everything defined in the stylesheet.



  • Just input the name of the object as id in stylesheet ex.

    @#MyList {
    background-color: #f0f0f0;
    }

    #MyList::item:selected {
    border: 1px solid #6a6ea9;
    border-radius: 4px;
    background-color: white;
    color: black;
    }@



  • That wasn't my question. The problem isn't that the stylesheet isn't associated with my object - if I just draw using the default delegate then it correctly picks up the style - the problem is that I'm unable to access the style from within a custom delegate.

    For example if I do this:

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

    Then the stylesheet is respected. However when I try to manually draw things, ie:

    @QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);
    QStyle* pStyle = opt.widget ? opt.widget->style() : QApplication::style();
    painter->save();
    pStyle->drawItemText(painter, opt.rect, Qt::AlignRight | Qt::AlignVCenter,
    pStyle->standardPalette(), true, "customText");
    painter->restore();@

    then the 'customText' is aligned all the way to the right, without respect for the padding defined in the style.

    How do I access the stylesheet from my delegate?



  • There is no standard way to do such things.
    If you know, the style sheet is assigned to the widget, you can use pWidget->styleSheet(). If the style sheet is assigned to a higher level widget of the application, you have to scan the hierarchy.

    But there is no way I know, to get that part of a style sheet that is needed for your specific element. The style sheet is once parsed by the style sheet style and then internally handled in a binary way. all that is done in private classes of QtGui.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.