1

我找到了一种在 QML 中嵌入 QWidget 的方法,方法是使用 QQuickWidget 渲染(锚定,具有 QQuickWidget 位置的 QWidget),但我正在尝试使用使用不同渲染系统的 QQuickView/QmlApplicationEngine 和 QWidget未显示。

有任何想法吗?提前致谢!

4

1 回答 1

0

评论中链接的帖子都没有回答我的问题。有这个小工作(对于那些需要它的人):

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

    QQmlApplicationEngine *engine = new QQmlApplicationEngine(&app);
    engine->load(QUrl("qrc:/qml/main.qml"));
    QQuickWindow* qmlwindow = qobject_cast<QQuickWindow *>(engine->rootObjects().first());

    CustomWidget *customwidget = new CustomWidget();
    QWindow* customwidgetwindow = QWindow::fromWinId(customwidget->winId());

    customwidgetwindow->setParent(qmlwindow);
    customwidget->show();

    if (window) {
        QQuickItem *qmlCustomWidget = qmlwindow->findChild<QQuickItem*>("qmlcustomwidget");
        if (qmlCustomWidget) {
            new WidgetAnchor(customwidgetwindow, qmlCustomWidget);
        }
    }

return app.exec();
}

其中 CustomWidget 是基于 QWidget 的类,而 WidgetAnchor.cpp 是:

WidgetAnchor::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();
}

void WidgetAnchor::updateGeometry() {
    if (_pQuickItem) {
        QRectF r = _pQuickItem->mapRectToItem(nullptr, QRectF(_pQuickItem->x(), _pQuickItem->y(), _pQuickItem->width(), _pQuickItem->height()));
    _pWidget->setGeometry(r.toRect());
    }
}

在 main.qml 你有:

import QtQuick 2.0
import QtQuick.Window 2.3

Window {
    id: root
    visible: true
    width: 500; height: 500

    Item {
        objectName: "qmlcustomwidget"
        anchors.fill: parent
    }
}
于 2019-12-02T11:17:12.767 回答