PDA

View Full Version : How to embed a QML based view onto a native window?



L440
9th August 2016, 16:37
Hello everyone,

I'm using the latest Qt 5.7 and I am having a bit of a problem with what would seem to be a relatively straight-forward task. I'm trying to embed a QML based view hierarchy onto a native application on OSX. Here's what I've tried so far:

I started simple. Just to launch a QQuickView, like so:



- (void)applicationDidFinishLaunching:(NSNotificatio n *)aNotification
{
// Insert code here to initialize your application
NSWindow* window = [[[NSApplication sharedApplication] windows] objectAtIndex:0];
NSView *view = [window contentView];

char* test[0];
int count = 0;

QApplication::instance()->setAttribute(Qt::AA_PluginApplication);
_qt = new QApplication(count, test);

_qml = new QQuickView();
_qml->setSource(QUrl(QStringLiteral("main.qml")));
_qml->setResizeMode(QQuickView::SizeRootObjectToView);
_qml->show();

_timer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(processEvents) userInfo:nil repeats:YES];
}


The qml is just a simple thing:



import QtQuick 2.7

Item
{
visible: true
x: 0;
y: 0;
width: 100
height: 100
Rectangle
{
id: rect
anchors.fill: parent
color: 'blue'
MouseArea
{
anchors.fill: parent
onClicked:
{
console.log(parent.color);
if(parent.color == '#0000ff')
parent.color = 'green';
else
parent.color = 'blue';
}
}
}
}



The timer is used to call processEvents and sendPostedEvents on the qt app instance. This works, however, it is launching its own window. What I'd like to do is embed this into the native window of the application. And this is where things don't work. I tried this:



NSView *view = [window contentView];
_qml = new QQuickView();
_qml->setSource(QUrl(QStringLiteral("main.qml")));
_qml->setResizeMode(QQuickView::SizeRootObjectToView);

[view addSubview:(NSView*)_qml->winId()];


This results in the QML indeed being inserted into the main view, but the rectangle is black and although it receives the clicks ( I see the logs) it doesn't render the rectangle properly (its supposed to change its color)

I also tried this, but it is not working either (launches a borderless window)



_qWindow = QWindow::fromWinId((WId)view);

_qml = new QQuickView(_qWindow);
_qml->setSource(QUrl(QStringLiteral("main.qml")));
_qml->setResizeMode(QQuickView::SizeRootObjectToView);
_qml->show();
_qWindow->show();


Can someone clue me in on how to achieve this? It 'should' be something easy that I'm missing. Could you provide an example ?

Thanks!