Adding a background image to a QQuickItem

2019-08-08 23:49发布

问题:

I have created a QPixmap and drawn smaller QPixmaps on it with QPainter. I want to use the image as the background of a QQuickItem. Is there an easy way to do this?

回答1:

If your custom item derived from QQuickItem you can redefine QQuickItem::updatePaintNode() in maybe this way:

QSGNode *MyItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *)
{
    QSGSimpleTextureNode *node = static_cast<QSGSimpleTextureNode *>(oldNode);
    if (!node) {
        node = new QSGSimpleTextureNode();
        QSGTexture *texture = window()->createTextureFromImage(m_pixmap.toImage());
        node->setTexture(texture);
    }
    node->setRect(boundingRect());
    return node;
}

Pay attention: your item is owner of QSGTexture *texture, don't forget to delete it while object destruction.



标签: qt qml qtquick2