How to add a Text{} element from C++ layer
-
I have a project in Qt 5.2.1 that needs a water stamp, a simple text element.
Since the project will be executed on windows computers, the qml will be exposed so I want to add a water stamp text box element from the C++ layer of the project. Is there a way to create an object like this…
Text {
text: “This text will be always added but will not be visible in the qml files”
.
.
}…in the C++ layer and add it at the bottom in the root Element in “main.qml”?
I tried to use the qrc file system in QT 5.4.0 as well (since it will embed the qml files into the exe-file) but it has some restrictions and creates other problems that will not work with my project currently.
-
Hi,
You can use QQmlComponent to create the Text element from C++ side. It provides "setData()":http://doc.qt.io/qt-5/qqmlcomponent.html#setData which can be used to load to QML data. Also set a parent to it.
-
I checked this page:
http://doc.qt.io/qt-5/qqmlcomponent.html
It seems that this solution a qml file will still be exposed since the component is loaded from a qml file outside the C++ layer.
Example from the link
@
void MyCppItem::init()
{
QQmlEngine *engine = qmlEngine(this);
// Or:
// QQmlEngine *engine = qmlContext(this)->engine();
QQmlComponent component(engine, QUrl::fromLocalFile("MyItem.qml"));
QQuickItem childItem = qobject_cast<QQuickItem>(component.create());
childItem->setParentItem(this);
}
@In the example the water stamp can be changed if MyItem.qml is modified (?).
Since I just want text as a water stamp is it possible to load/use the "built-in" qml file used for Text-elements?
-
The QQmlComponent::setData() function p3c0 referred to takes a QByteArray containing the QML source of the component. The QUrl is for naming and resolution of child components.
@
QQmlComponent component(engine);
QByteArray data("Text { text:"watermark"}");
component.setData(data, QUrl());
@Putting the file in a qrc also works.
-
Putting it in qrc will also not work as there are tools that can print the strings present in any binary file.
One way would be to keep the QML string (as shown above) in the encrypted format and then while passing it to setData(), decrypt it. -
Yes, putting strings in an executable does make them vulnerable to discovery and modification. So does embedding a decryption key, or the cipher text encrypted with a known or constant key.
There are a number of simple attacks that can work with any of these schemes, and unless each user is given a different executable, broken for one is broken for all.
The question is how much development hassle and runtime overhead is reasonable.
-
That's true. The ultimate security would be to use the Qt Quick Compiler but that's available in commericial version. Recently I came across "qmlc":https://github.com/qmlc/qmlc. Anyone tried it ?