2

作成したカスタムQQuickItemがあり、角の丸いウィンドウを作成したいと考えていました。そこで、 を実装してQQuickPaintedItemにエクスポートしましたQML。問題は、アイテムの子がアイテムの境界四角形によって拡大していることです。これは四角形であり、私が望むような角の丸い四角形ではありません。外観は次のとおりです。

ここに画像の説明を入力

これが私のコードです:

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の角が私のカスタム形状(この場合は角の丸い長方形)によって切り取られることです。このようなもの:

ここに画像の説明を入力

でこのようなことを達成することは可能QMLですか?

4

1 に答える 1

9

QQuickPaintedItem で可能かどうかはわかりませんが(境界線のみではなく塗りつぶしを使用する必要があります)、カスタム QSGNode を作成せずに(非常にハック)、唯一の方法はopacitymaskを使用することです:

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

これにより、次のことが得られます。

マスクされて切り取られた長方形

ただし、内部アイテムとマスクを最初にバッファーに描画してからウィンドウに再描画する必要があるため、これを使用すると GPU を消費するタスクになるため、古いモバイル デバイスや弱い組み込みデバイスにはあまり適していません。

于 2016-09-12T18:48:19.243 に答える