Qml定义自定义属性组

时间:2015-10-05 21:03:46

标签: qml qt5

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

使用示例:

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

1 个答案:

答案 0 :(得分:1)

我担心这并不像你想象的那么简单。

据我所知,您有两种选择:

1.-遵循您将在@BaCaRoZzo提供的link中看到的建议并实施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"
    }    
}