有没有办法将QWidget嵌入到QQmlApplicationEngine或QQuickView中?



我找到了一种将QWidget嵌入QML的方法,通过使用QQuickWidget渲染(锚定,QWidget与QQuickWidget位置(,但我正在尝试使用QQuickView/QmlApplicationEngine做同样的事情,它使用不同的渲染系统,并且QWidget没有显示。

有什么想法吗?提前感谢!

评论中链接的帖子都没有回答我的问题。有一个小的解决方法(对于那些需要它的人(:

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
}
}

相关内容

  • 没有找到相关文章

最新更新