What is the best way to display an animated icon in a QTableView?

后端 未结 5 1444
生来不讨喜
生来不讨喜 2021-02-05 19:54

I\'ve been struggling with this for some times now, and I can\'t seem to find the right way to do this.

What I would like is the ability to use an animated icon as a dec

5条回答
  •  旧时难觅i
    2021-02-05 20:15

    The best solution is to use QSvgRenderer within delegate.

    It's very easy to implement and unlike gif, SVG is lightweight and supports transparency.

        TableViewDelegate::TableViewDelegate(TableView* view, QObject* parent)
        : QStyledItemDelegate(parent), m_view(view)
    {
        svg_renderer = new QSvgRenderer(QString{ ":/res/img/spinning_icon.svg" }, m_view);
    
        connect(svg_renderer, &QSvgRenderer::repaintNeeded,
            [this] {
            m_view->viewport()->update();
        });
    }
    
    
    void TableViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
        const QModelIndex& index) const
    {
        QStyleOptionViewItem opt{ option };
        initStyleOption(&opt, index);
    
        if (index.column() == 0) {
            if (condition)
            {
                // transform bounds, otherwise fills the whole cell
                auto bounds = opt.rect;
                bounds.setWidth(28);
                bounds.moveTo(opt.rect.center().x() - bounds.width() / 2,
                    opt.rect.center().y() - bounds.height() / 2);
    
                svg_renderer->render(painter, bounds);
            }
        }
    
        QStyledItemDelegate::paint(painter, opt, index);
    }
    

    Here's a nice website where you can generate your own spinning icon and export in SVG.

提交回复
热议问题