I've found this example of how to display a QWidget (specifically a QLabel) inside a QML document:
https://kunalmaemo.blogspot.com/2011/07/how-to-display-qwidget-into-qml.html
The problem is that this uses QtQuick 1 and won't compile in my application (which is using QtQuick 2).
How can I do this using QtQuick 2? I need to do exactly what this original sample does: create a QLabel
on the c++ side and embed it in a QML document.
Here is what I've been able to do so far. This is similar to the example I posted above, except there is no QGraphicsProxyWidget* mProxy;
since it doesn't compile in QtQuick 2, and I made this a QQuickView
instead of a QDeclarativeItem
for the same reason. On the c++ side I've defined a class named QmlLabel
.
Header:
class QmlLabel : public QQuickView
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText)
public:
explicit QmlLabel(QQuickView *parent = 0);
~QmlLabel();
public slots:
void setText(const QString& text);
QString text() const;
private:
QLabel* mLabel;
};
Implementation:
QmlLabel::QmlLabel(QQuickView *parent) :
QQuickView(parent)
{
mLabel = new QLabel(QString(""));
mLabel->setText("Your mother sews socks");
mLabel->setStyleSheet("QLabel { background-color : red; color :
blue; white-space : pre-wrap; }");
}
QmlLabel::~QmlLabel()
{
delete mLabel;
}
void QmlLabel::setText(const QString& text)
{
mLabel->setText(text);
}
QString QmlLabel::text() const
{
return mLabel->text();
}
I'm calling qmlRegisterType
for this class, and this allows me to declare an object of type QmlLabel
in my QML file like so:
QmlLabel {
id: whatever
height: 50
width: 200
}
Everything compiles, builds and runs, but the QmlLabel is not visible at all. Obviously there is no code in the constructor that actually adds the created QLabel
to anything, so even though the label is created successfully it would not be visible without being added to anything. This line in the original example:
mProxy = new QGraphicsProxyWidget(this);
mProxy->setWidget(mLabel);
... is presumably why the label shows up, but I can't call this without QGraphicsProxyWidget to add it to.
So how can I make this work?