在自定义形状后剪辑自定义qml项目的子项

时间:2016-09-12 17:39:14

标签: c++ qt qml qtquick2 qquickitem

我创建了一个自定义QQuickItem,我想创建一个圆形的角落窗口。所以我实施了QQuickPaintedItem并导出到QML。问题是项目的孩子正在通过项目的边界矩形进行扩展,这是一个矩形而不是我想要的圆角矩形。这是它的外观:

enter image description here

这是我的代码:

main.qml

import QtQuick 2.7
import QtQuick.Window 2.2
import mycustomlib 1.0

Window {
    id: wnd
    width: 300
    height: 280
    visible: true
    flags: Qt.FramelessWindowHint
    color: "transparent"
    x: 250
    y: 250

    MyCustomWindow {
        id: playerFrame
        anchors.fill: parent
        radius: 25

        Rectangle {
            color: "beige"
            anchors.margins: 5
            anchors.fill: parent
        }
    }
}

的main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QUrl>

#include "mycustomwindow.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<MyCustomWindow>("mycustomlib", 1, 0, "MyCustomWindow");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

mycustomwindow.h

#ifndef MYCUSTOMWINDOW_H
#define MYCUSTOMWINDOW_H

#include <QQuickPaintedItem>

class MyCustomWindow : public QQuickPaintedItem
{
    Q_OBJECT

    Q_PROPERTY(int radius READ radius WRITE setRadius NOTIFY radiusChanged)

public:
    MyCustomWindow(QQuickItem *parent = 0);

    int radius() const;
    void setRadius(int radius);

signals:
    void radiusChanged();

protected:
    virtual void paint(QPainter *pPainter) Q_DECL_OVERRIDE;

private:
    int m_radius;
};

#endif // MYCUSTOMWINDOW_H

mycustomwindow.cpp

#include "mycustomwindow.h"

#include <QPainter>

MyCustomWindow::MyCustomWindow(QQuickItem *parent) :
    QQuickPaintedItem(parent),
    m_radius(0)
{
    setAcceptedMouseButtons(Qt::AllButtons);
}

void MyCustomWindow::paint(QPainter *pPainter)
{
    const QRect myRect(0, 0, width() - 1, height() - 1);
    pPainter->fillRect(myRect, Qt::transparent);
    pPainter->drawRoundedRect(myRect, m_radius, m_radius);
}

int MyCustomWindow::radius() const
{
    return m_radius;
}

void MyCustomWindow::setRadius(int radius)
{
    m_radius = radius;

    emit radiusChanged();
}

我想要的是,我的自定义形状(在这种情况下是一个圆角矩形)将儿童Rectangle逼入角落。这样的事情:

enter image description here

是否有可能在QML中实现这样的目标?

1 个答案:

答案 0 :(得分:4)

我不知道QQuickPaintedItem是否可行(它应该使用fill,而不是仅使用border),但是如果不创建自定义QSGNode(非常hacky),唯一的方法是使用{{3} }:

Rectangle{
    id: mask
    width:100
    height: 100
    radius: 30
    color: "red"
    border.color: "black"
    border.width: 1
}

Item {
    anchors.fill: mask
    layer.enabled: true
    layer.effect: OpacityMask {
        maskSource: mask
    }
    Rectangle {
        anchors.fill: parent
        anchors.margins: 5
        color:"yellow"
    }
}

这给了你:

masked and clipped rectangle

但是使用它将是GPU消耗任务,因为内部项目和掩码必须首先在缓冲区上绘制然后重新绘制在窗口上,因此对于旧的移动设备或弱嵌入式设备来说不是很好。