向 QQuickItem 添加背景图像

Adding a background image to a QQuickItem

我创建了一个 QPixmap 并在上面用 QPainter 绘制了更小的 QPixmap。我想用图片作为背景QQuickItem。是否有捷径可寻?

如果您的自定义项目源自 QQuickItem,您可以这样重新定义 QQuickItem::updatePaintNode()

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;
}

注意:你的物品是QSGTexture *texture的拥有者,不要忘记在对象销毁时删除它。