QML剪辑自定义项

时间:2018-02-15 08:22:28

标签: qt qml qtquick2

我制作了自己的QQuickItem,我使用updatePaintNode方法绘制(使用场景图)。在qml文件中,我将此项目作为子项添加到Rectangle:

    Rectangle {
        anchors.centerIn: parent
        width: parent.width/2.
        height: parent.height/2.
        border.color: "#000000"
        clip: true

        MyItem {
            id: myitem
            anchors.centerIn: parent
            width: parent.width
            height: parent.height
            MouseArea {
                anchors.fill: parent
                onWheel: {
                    if (wheel.modifiers & Qt.ControlModifier) {
                        parent.scale = parent.scale+ 0.2 * wheel.angleDelta.y / 120;
                        if (parent.scale < 1)
                            parent.scale = 1;
                    }
                }

            }
        }
    }

如您所见,我添加了缩放功能并设置

    clip: True

表示矩形。但是,当我缩放时,我的项目不会在矩形处剪切,而是延伸到矩形之外。做剪辑的正确方法是什么?

编辑:这是MyItem

的cpp文件的内容
MyItem::MyItem(QQuickItem *parent): QQuickItem(parent)
{
    setFlag(QQuickItem::ItemHasContents,true);
    // code to initialize xdata, ydata, xmax, ymax

}

QSGNode *MyItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) {
    QSGGeometryNode *mypath = static_cast<QSGGeometryNode*>(oldNode);
    if(!mypath) {
       mypath = new QSGGeometryNode;
       mypath->setFlag(QSGNode::OwnsMaterial,true);
       mypath->setFlag(QSGNode::OwnsGeometry,true);
    }
    QSGGeometry *geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(),_xdata.size());
    QSGGeometry::Point2D *points = geometry->vertexDataAsPoint2D();
    for(int i=0;i<_xdata.size();i++) {
    points[i].x = _xdata[i]/_xmax*width();
    points[i].y = _ydata[i]/_ymax*height();
    }
    geometry->setLineWidth(2);
    geometry->setDrawingMode(GL_LINE_STRIP);
    mypath->setGeometry(geometry);
    QSGFlatColorMaterial *material = new QSGFlatColorMaterial;
    material->setColor(Qt::blue);
    mypath->setMaterial(material);
    return mypath;
}

这是头文件:

#include <QQuickItem>
#include <vector>

class MyItem : public QQuickItem
{
    Q_OBJECT
public:
    MyItem(QQuickItem *parent = 0);

private:
    std::vector<double> _xdata;
    std::vector<double> _ydata;
    double _xmax;
    double _ymax;

signals:

public slots:

protected:
    QSGNode * updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data) override;
};

0 个答案:

没有答案