Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Declarative Widgets

adding Qt Widgets support to QML

import QtWidgets 1.0

MainWindow {
    width: 640
    height: 400

    Label {
        text: "Hello Declarative Widgets!"
        alignment: Qt.AlignHCenter | Qt.AlignVCenter
    }
}
import QtWidgets 1.0

GroupBox {
    title: qsTr("New Contact: %1 %2").arg(firstName.text).arg(lastName.text)

    FormLayout {
        LineEdit {
            id: firstName
            FormLayout.label: qsTr("First Name")
        }
        LineEdit {
            id: lastName
            FormLayout.label: qsTr("Last Name")
        }
    }
}
qmlRegisterExtendedType<QWidget, DeclarativeWidgetExtension>(uri, 1, 0, "Widget");
class DeclarativeWidgetExtension : public DeclarativeObjectExtension
{
    Q_OBJECT

    // repeat property declarations, qmlRegisterExtendedType doesn't see the ones from base class
    Q_PROPERTY(QQmlListProperty<QObject> data READ data DESIGNABLE false CONSTANT)

    Q_PROPERTY(int x READ x WRITE setX NOTIFY posChanged)
    Q_PROPERTY(int y READ y WRITE setY NOTIFY posChanged)
    Q_PROPERTY(int width READ width WRITE setWidth NOTIFY sizeChanged)
    Q_PROPERTY(int height READ height WRITE setHeight NOTIFY sizeChanged)
    Q_PROPERTY(QRect geometry READ geometry WRITE setGeometry NOTIFY geometryChanged)
    Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged)

    Q_CLASSINFO("DefaultProperty", "data")
}
QWidget *DeclarativeWidgetExtension::extendedWidget() const
{
    QWidget *parentWidget = qobject_cast<QWidget*>(parent());
    Q_ASSERT(parentWidget);
    Q_UNUSED(parentWidget);

    return parentWidget;
}

int DeclarativeWidgetExtension::x() const
{
    return extendedWidget()->x();
}

void DeclarativeWidgetExtension::setX(int value)
{
    QWidget *widget = extendedWidget();

    if (value == widget->x())
      return;

    QRect geometry = widget->geometry();
    geometry.moveLeft(value);
    widget->setGeometry(geometry);
}
bool DeclarativeWidgetExtension::eventFilter(QObject *watched, QEvent *event)
{
    Q_ASSERT(watched == parent());
    Q_UNUSED(watched);

    switch (event->type())
    {
    case QEvent::Move:
        emit posChanged();
        emit geometryChanged();
        break;

    case QEvent::Resize:
        emit sizeChanged();
        emit geometryChanged();
        break;

    case QEvent::Show:
    case QEvent::Hide:
        emit visibleChanged(isVisible());
        break;

    default:
        break;
    }

    return false;
}

14 Comments

5 - Apr - 2018

Alexxey593

6 - Apr - 2018

Alex

6 - Apr - 2018

js

9 - Apr - 2018

Kevin Krammer

25 - Apr - 2018

Ernesto

25 - Apr - 2018

Nathan Collins

4 - Nov - 2020

Aleksey

4 - Nov - 2020

Nathan Collins

4 - Nov - 2020

Aleksey

18 - Jan - 2021

Nathan Collins

27 - Aug - 2022

SC

31 - Aug - 2022

Nathan Collins

23 - Oct - 2022

Faisal

24 - Oct - 2022

Nathan Collins