在QML 中,嵌入QWidget 对象

场景:QML 目前还不够强大 有些需求无法满足,比如把MFC窗口嵌入到程序中,但是QWidget已经很成熟了,所以类似得痛点需要把QWidget嵌入到QML中。

 

以下为:将PPT通过QWidget 嵌入到QML中

 

一,QML文件加载 使用 QQuickWidget + Rectangle的形式,因为QQuickWidget 是继承于QWidget(详情参考:https://blog.csdn.net/weixin_38416696/article/details/105432525)

,qml文件中,放置一个Item用户接收QWidget

Item {

    ... // layouts, extra items, what have you

        Item
        {
            objectName: "widgetItem"
            anchors.fill: parent
        }

    ... // more layouts, extra items, etc.
}

,新建一个继承自QObject的类,用于控制widget的位置和大小

class WidgetAnchor: public QObject
{
    QPointer _pWidget;
    QPointer _pQuickItem;
public:
    WidgetAnchor(QWidget* pWidget, QQuickItem* pItem)
        : QObject(pWidget), _pWidget(pWidget), _pQuickItem(pItem)
    {
        connect(_pQuickItem, &QQuickItem::xChanged, this, &WidgetAnchor::updateGeometry);
        connect(_pQuickItem, &QQuickItem::yChanged, this, &WidgetAnchor::updateGeometry);
        connect(_pQuickItem, &QQuickItem::widthChanged, this, &WidgetAnchor::updateGeometry);
        connect(_pQuickItem, &QQuickItem::heightChanged, this, &WidgetAnchor::updateGeometry);
        updateGeometry();
    }
private:
    void updateGeometry()
    {
        if (_pQuickItem)
        {
            QRectF r = _pQuickItem->mapRectToItem(0, QRectF(_pQuickItem->x()- _pQuickItem->width()/2, _pQuickItem->y()-_pQuickItem->height()/2, _pQuickItem->width(), _pQuickItem->height()));
            _pWidget->setGeometry(r.toRect());
        }
    }
};

四,main.cpp

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

    auto pqw = new QQuickWidget;
    pqw->setSource(QUrl::fromLocalFile("main.qml"));
    pqw->setResizeMode(QQuickWidget::SizeRootObjectToView);
    pqw->setAttribute(Qt::WA_DeleteOnClose);
    auto pOwt = new MyWidget(pqw); // 自定义 widget窗体
    if (auto pOverlayItem = pqw->rootObject()->findChild("widgetItem"))
        new WidgetAnchor(pOwt, pOverlayItem);
    pqw->show();

    return app.exec();
}

 

参考:https://www.thinbug.com/q/13014415

你可能感兴趣的:(Qt)