Qml 定义自定义 属性 组

Qml define custom property group

如何在 qml 中定义自定义 属性 组,等于锚点 属性?

用法示例:

Item {
  anchors {
    leftMargin: 5
    rightMargin: 5
  }
}

恐怕这并不像你想象的那么简单。

据我所知,你有两个选择:

1.- 遵循您将在 provided by @BaCaRoZzo and implement your own object type 中看到的建议。

2.- 用 C++ 编写更复杂的 QML 类型并在您的 QML 文件中使用它。或多或少是@folibis 指出的想法。示例:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include "customitem.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<CustomItem>("CustomItem", 1,0, "CustomItem");

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

    return app.exec();
}

customitem.h

#ifndef CUSTOMITEM_H
#define CUSTOMITEM_H

#include <QObject>

class CustomItem: public QObject
{
    Q_OBJECT

    /*
     * Any property that is writable should have an associated NOTIFY signal.
     * Ref: http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html#exposing-properties
     */

    Q_PROPERTY(int x READ x WRITE setX NOTIFY xChanged)
    Q_PROPERTY(int y READ y WRITE setY NOTIFY yChanged)


public:
    CustomItem(QObject *parent = 0);

    int x() const;
       void setX(int);

       int y() const;
       void setY(int);

private:
    int m_x;
    int m_y;

signals:
    void xChanged();
    void yChanged();

public slots:
};

#endif // CUSTOMITEM_H

customitem.cpp

#include "customitem.h"

CustomItem::CustomItem(QObject *parent)
: QObject(parent), m_x(0), m_y(0)
{
}

int CustomItem::x() const
{
    return m_x;
}

void CustomItem::setX(int x)
{
    m_x = x;
}

int CustomItem::y() const
{
    return m_y;
}

void CustomItem::setY(int y)
{
    m_y = y;
}

main.qml

import QtQuick 2.5
import QtQuick.Window 2.2
import CustomItem 1.0

Window {
    visible: true

    CustomItem {
        id: customItem
        x: 50
        y: 50
    }

    Rectangle {
        id: rect
        x: customItem.x
        y: customItem.y
        width: 100; height: 100
        color: "red"
    }    
}