How to separate design and logic of Repeater in QML - qt

When using QML, Qt Creator advises to separate design and logic into 2 QML files, e.g. a File.qml and FileForm.ui.qml, the former for logic, the latter for design. It can only show a file in visual designer if it does not contain complex code, like function calls or {} code blocks (I'm using Qt creator 4.5.2 that comes with Ubuntu 18.04).
Now for the question: how do I move complex code out of ui.qml when I use Repeater and its delegates?
Example:
My FileForm.ui.qml looks like this:
import "displayutils.js" as Utils
RowLayout {
property alias rr: rr
property alias tt: tt
Repeater {
id: rr
Text {
id: tt
text: "text: "+ Utils.fmtTemp(modelData.temp)+" / "+Utils.fmtPressure(modelData.pressure)
}
}
}
I instantiate it in File.qml like this:
File {
Component.onCompleted: {
rr.model = ... // some model from C++ code, does not matter.
}
}
Now, Qt Creator does not want to open FileForm.ui.qml file because of complex formatting of text and I have to move it to File.qml. How do I do this correctly? Whatever I tried, I loose modelData object from Repeater. I tried various variants of this:
File {
tt.text = someFunction(modelData)
Component.onCompleted: {
rr.model = ... // some model from C++ code, does not matter.
}
}

I find this separation very helpful and use it all of the time. You can do it in this case by separating out the Repeater's children like this:
RepeaterTextForm.ui.qml:
Text {}
RepeaterText.qml:
import "displayutils.js" as Utils
RepeaterTextForm {
text: (
"text: " +
Utils.fmtTemp(modelData.temp) +
" / " +
Utils.fmtPressure(modelData.pressure)
)
}
FileForm.ui.qml:
RowLayout {
property alias rr: rr
Repeater {
id: rr
RepeaterText {}
}
}
File.qml:
File {
Component.onCompleted: {
rr.model = ... // some model from C++ code, does not matter.
}
}

Related

Dynamically retranslate Qt Quick UI

I want to dynamically retranslate Qt Quick GUI strings.
There is intrusive trick to retranslate affected string properties, whose notifications about changes cannot be centralized.
Is it possible to make qsTr (and others) to return string-like objects, which behaves exactly like string, but also behaves like global properties connected to common "valueChanged" signal (which I want to emit, when QEvent::LanguageChange in QCoreApplication occured).
I think I can use twitching of Loader's active property, which contains entire top level GUI element to make all the user-visible strings retranslated, but this approach results in lost of the state of all the items and components, connected to the Loader and not differs from complete application restart for me.
Is it possble to create such myQsTr function?
From Qt 5.10 onwards, you can call QQmlEngine::retranslate() after you have installed a new translator with QCoreApplication::installTranslator(), to ensure that your user-interface shows up-to-date translations.
You could opt to use your own, 100% QML solution like that:
// Tr.qml
// also put `singleton Tr Tr.qml` in the qmldir file
pragma Singleton
import QtQuick 2.7
QtObject {
function t(s) {
if (lang === eng) return s
var ts = lang[s]
return ts ? ts : s
}
property var lang: eng
readonly property var eng : {
"hello" : "hello",
"goodbye" : "goodbye"
}
readonly property var ger : {
"hello" : "hallo",
"goodbye" : "auf wiedersehen"
}
readonly property var esp : {
"hello" : "hola"
}
}
// test it out
import QtQuick 2.7
import QtQuick.Controls 2.1
import "." // same old singleton bug
ApplicationWindow {
id: main
visible: true
width: 640
height: 480
color: "darkgray"
Column {
Text { text: Tr.t("hello") }
Text { text: Tr.t("goodbye") }
Button { text: "Eng"; onClicked: Tr.lang = Tr.eng }
Button { text: "Ger"; onClicked: Tr.lang = Tr.ger }
Button { text: "Esp"; onClicked: Tr.lang = Tr.esp }
}
}
The different language objects act like a map<string, string> and every time you change lang this will cause the binding expressions to reevaluate and refresh the value form the current language dictionary.
This solution will also fallback to the default language string if a translation is not found. You can easily customize the behavior and you don't rely on any external tooling. Clean, simple, self-contained and totally under your control.

Custom attached properties in QML

I'm creating a custom QML component (a specialization of ListView that allows multiple selection). I'd like to provide attached properties to objects provided to my component. I see how to create attached properties using C++. However, I cannot find information on adding custom properties in pure QML. Is this possible using QML?
Is this possible using QML?
No.
There is an alternative, easy and clean way to this in QML - just use an adapter object that implements the desired properties. Then instead of attaching just nest into the adapter - use it as as a parent / container. You can also nest objects into the adapter, getting another C++ exclusive - grouped properties. A possible way to minimize the overhead of this is to use JS objects and properties, with a downside - no change notifications, which you can somewhat mitigate by emitting manually.
An example:
// Adapter.qml - interface with attached properties
Item {
id: adapter
property int customInt : Math.random() * 1000
property var group : {"a" : Math.random(), "b" : Math.random() }
default property Component delegate
width: childrenRect.width
height: childrenRect.height
Component.onCompleted: delegate.createObject(adapter)
}
// usage
ListView {
width: 100
height: 300
model: 5
delegate: Adapter {
Row {
spacing: 10
Text { text: index }
Text { text: customInt }
Text { text: group.a }
Text { text: group.a }
}
}
}
It is fairly painless and convenient compared to some other QML workarounds. You don't even have to do parent.parent.customInt - the properties are directly accessible as if they are attached, this works because of dynamic scoping. The default property allows to avoid setting the inner delegate as a property you just nest the delegate you want directly in the adapter.
In many cases those acrobatics are overkill, you can just wrap in place:
ListView {
width: 100
height: 300
model: 5
delegate: Item {
width: childrenRect.width
height: childrenRect.height
property string custom1: "another"
property string custom2: "set of"
property string custom3: "properties"
Row {
spacing: 10
Text { text: index }
Text { text: custom1 }
Text { text: custom2 }
Text { text: custom3 }
}
}
}
The only key part really is the binding for the size of the adapter object so that the view can properly layout the objects. I routinely use a Wrap element which essentially does the same but is implemented in C++, which is much more efficient than a QML binding.

QML send signals between anonymous grandchildren

I'm trying to communicate between qml components in a tree structure. I have a main.qml component with and id of root. It has two children, and each of those children has an arbitrary number of children dynamically created from a repeater and a model.
When one of the grandchildren is clicked I would like the others to know, and be able to take action. So if I could send signals between the grandchildren that would be fine.
The problem is none of them have their id property set because they are made dynamically, and some of them are in different scopes. To communicate between them I have done the following:
Created a function in root, every grandchild can see that, and can call it with a message as parameter. The root function then emits a signal with the message as parameter. All the grandchildren can connect to the signal because they know the id of root.
What do people think of that? I'm getting the feeling that I've missed the point of signals in qml, feels like i've implemented a crude system and missed the whole point or something.
Also, I want to stay out of the C++ world, but do people think it would be best to use a C++ class so that I can use signals and slots.
What I'm aiming at is an MVC structure with very loose coupling, and a centralised Controller. What do people think about communicating between QML components in MVC.
The only similar questions I found here were about C++ or using hard-coded id's on components.
I don't think id's can be set dynamically, not even once at creation; am I wrong about that?
Also, the components are in different scopes, so id's can't be resolved; am I wrong about that?
I've written some code:
//qml.main
import QtQuick 2.4
import QtQuick.Controls 1.3
ApplicationWindow {
id: root
visible: true
menuBar: MenuBar {
Menu {
title: qsTr("File")
MenuItem {
text: qsTr("&Open")
onTriggered: console.log("Open action triggered");
}
MenuItem {
text: qsTr("Exit")
onTriggered: Qt.quit();
}
}
}
property string thisName: "root"
signal rootSays(string broadcastMessage)
function callRoot(message) {
var response = message
print("Root received: " + message)
print("Root broadcasting: " + response)
rootSays(response)
}
MajorComponent{//this is root's child A
property string thisName: "A"
thisModel: [{name:"First Grandchild of A", color:"red", y:0},
{name:"Second Grandchild of A", color:"green", y:80}]
}
MajorComponent{//this is root's child B
property string thisName: "B"
thisModel: [{name:"First Grandchild of B", color:"blue", y:210},
{name:"Second Grandchild of B", color:"yellow", y:290}]
}
}
//qml.MinorComponent
import QtQuick 2.0
Rectangle {
property string thisName: ""
property string thisColor: ""
color: thisColor
height: 50; width: 200
Text {
anchors.centerIn: parent
text: thisName
}
MouseArea {
anchors.fill: parent
onClicked: {
print(thisName + " clicked")
print("Root called with: " + thisName)
root.callRoot("Hello from " + thisName)
print("---")
}
}
}
//qml.MajorComponent
import QtQuick 2.0
Rectangle {
property var thisModel: []
Repeater {
model:thisModel
MinorComponent {
y: modelData.y
thisName: modelData.name
thisColor: modelData.color
function handleResponse(response) {
print(thisName + " received: " + response);
}
Connections {
target: root
onRootSays: handleResponse(broadcastMessage)
}
}
}
}
I don't think id's can be set dynamically, not even once at creation;
am I wrong about that?
ids are purely "compile" time construct. That being said, there is nothing preventing you from implementing and managing your own object registry system. A simple empty JS object would do, it can effectively be used as a QMap to lookup objects based on a key (the property name). If you set the map object as a property of the root object, it should be resolvable from every object in the tree because of dynamic scoping.
The approach with the signal is a sound one IMO. I've used something similar, combined with functors and capture by reference, allowing access to arbitrary and optionally existing objects in an arbitrary tree structure, filtering candidates by various criteria they must meet. You can do some very tricky stuff with this technique.
That being said, a practical example which illustrates what you actually want to achieve will be useful for providing a more specific answer.

Qt 5 QML app with lots of Windows or complex UIs

In QtQuick 2 using the QtQuick Controls you can create complex desktop apps. However it seems to me that the entire UI must be declared and create all at once at the start of the app. Any parts that you don't want to use yet (for example the File->Open dialog) must still be created but they are hidden, like this:
ApplicationWindow {
FileDialog {
id: fileOpenDialog
visible: false
// ...
}
FileDialog {
id: fileSaveDialog
visible: false
// ...
}
// And so on for every window in your app and every piece of UI.
Now, this may be fine for simple apps, but for complex ones or apps with many dialogs surely this is a crazy thing to do? In the traditional QtWidgets model you would dynamically create your dialog when needed.
I know there are some workarounds for this, e.g. you can use a Loader or even create QML objects dynamically directly in javascript, but they are very ugly and you lose all the benefits of the nice QML syntax. Also you can't really "unload" the components. Well Loader claims you can but I tried it and my app crashed.
Is there an elegant solution to this problem? Or do I simply have to bite the bullet and create all the potential UI for my app at once and then hide most of it?
Note: this page has information about using Loaders to get around this, but as you can see it is not a very nice solution.
Edit 1 - Why is Loader suboptimal?
Ok, to show you why Loader is not really that pleasant, consider this example which starts some complex task and waits for a result. Suppose that - unlike all the trivial examples people usually give - the task has many inputs and several outputs.
This is the Loader solution:
Window {
Loader {
id: task
source: "ComplexTask.qml"
active: false
}
TextField {
id: input1
}
TextField {
id: output1
}
Button {
text: "Begin complex task"
onClicked: {
// Show the task.
if (task.active === false)
{
task.active = true;
// Connect completed signal if it hasn't been already.
task.item.taskCompleted.connect(onTaskCompleted)
}
view.item.input1 = input1.text;
// And several more lines of that...
}
}
}
function onTaskCompleted()
{
output1.text = view.item.output1
// And several more lines...
// This actually causes a crash in my code:
// view.active = false;
}
}
If I was doing it without Loader, I could have something like this:
Window {
ComplexTask {
id: task
taskInput1: input1.text
componentLoaded: false
onCompleted: componentLoaded = false
}
TextField {
id: input1
}
TextField {
id: output1
text: task.taskOutput1
}
Button {
text: "Begin complex task"
onClicked: task.componentLoaded = true
}
}
That is obviously way simpler. What I clearly want is some way for the ComplexTask to be loaded and have all its declarative relationships activated when componentLoaded is set to true, and then have the relationships disconnected and unload the component when componentLoaded is set to false. I'm pretty sure there is no way to make something like this in Qt currently.
Creating QML components from JS dynamically is just as ugly as creating widgets from C++ dynamically (if not less so, as it is actually more flexible). There is nothing ugly about it, you can implement your QML components in separate files, use every assistance Creator provides in their creation, and instantiate those components wherever you need them as much as you need them. It is far uglier to have everything hidden from the get go, it is also a lot heavier and it could not possibly anticipate everything that might happen as well dynamic component instantiation can.
Here is a minimalistic self-contained example, it doesn't even use a loader, since the dialog is locally available QML file.
Dialog.qml
Rectangle {
id: dialog
anchors.fill: parent
color: "lightblue"
property var target : null
Column {
TextField {
id: name
text: "new name"
}
Button {
text: "OK"
onClicked: {
if (target) target.text = name.text
dialog.destroy()
}
}
Button {
text: "Cancel"
onClicked: dialog.destroy()
}
}
}
main.qml
ApplicationWindow {
visible: true
width: 200
height: 200
Button {
id: button
text: "rename me"
width: 200
onClicked: {
var component = Qt.createComponent("Dialog.qml")
var obj = component.createObject(overlay)
obj.target = button
}
}
Item {
id: overlay
anchors.fill: parent
}
}
Also, the above example is very barebone and just for the sake of illustration, consider using a stack view, either your own implementation or the available since 5.1 stock StackView.
Here's a slight alternative to ddriver's answer that doesn't call Qt.createComponent() every time you create an instance of that component (which will be quite slow):
// Message dialog box component.
Component {
id: messageBoxFactory
MessageDialog {
}
}
// Create and show a new message box.
function showMessage(text, title, modal)
{
if (typeof modal === 'undefined')
modal = true;
// mainWindow is the parent. We can also specify initial property values.
var messageDialog = messageBoxFactory.createObject(mainWindow, {
text: text,
title: title,
visible: true,
modality: modal ? Qt.ApplicationModal : Qt.NonModal
} );
messageDialog.accepted.connect(messageDialog.destroy);
messageDialog.rejected.connect(messageDialog.destroy);
}
I think loading and unloading elements is not actual any more because every user have more than 2GB RAM.
And do you think your app can take more than even 512 MB ram? I doubt it.
You should load qml elements and don't unload them, no crashes will happens, just store all pointers and manipulate qml frames.
If you just keep all your QML elements in RAM and store their states, it will works faster and looks better.
Example is my project that developed in that way: https://youtube.com/watch?v=UTMOd2s9Vkk
I have made base frame that inherited by all windows. This frame does have methods hide/show and resetState. Base window does contains all child frames, so via signal/slots other frames show/hide next required frame.

Qt High Score System

I'm still quite new to Qt and I want to add a High Score system to my game. I found this file http://grip.espace-win.net/doc/apps/qt4/html/demos-declarative-snake-content-highscoremodel-qml.html which is a high score model qml element. I have have added it to my project but I am at an utter loss on how to implement it. I simply want to know how I can use it to show a High Score Table when my window goes to a certain state. I also want to know how to add scores and close it when the game is restarted. This my seem silly but I really can't figure out how to use it.
From the linked file above:
Use this component like this:
HighScoreModel {
id: highScores
game: "MyCoolGame"
}
Then ... use the model in a view:
ListView {
model: highScores
delegate: Component {
... player ... score ...
}
}
So by slightly altering the simpler of the two examples given in the QML ListView docs, we get:
import QtQuick 1.0
ListView {
width: 180; height: 200
model: highScores {}
delegate: Text {
text: player + ": " + score
}
}
Though if you want further control over the formatting of each element of the list, as suggested by the use of delegate: Component in the example quoted above from HighScoreModel.qml, the second usage example in the documentation shows you how.
You can also have a look at V-Play Engine for qt-based apps and games. It comes with many components to make mobile development easier.
You can also add leaderboards and user profiles to your application with a few lines of code:
import VPlay 2.0
import VPlayApps 1.0
import QtQuick 2.9
App {
// app navigation
Navigation {
NavigationItem {
title: "User Profile"
icon: IconType.user
NavigationStack {
initialPage: socialView.profilePage
}
}
NavigationItem {
title: "Leaderboard"
icon: IconType.flagcheckered
NavigationStack {
initialPage: socialView.leaderboardPage
}
}
}
// service configuration
VPlayGameNetwork {
id: gameNetwork
gameId: 285
secret: "AmazinglySecureGameSecret"
// increase leaderboard score by 1 for each app start
Component.onCompleted: gameNetwork.reportRelativeScore(1)
}
// social view setup
SocialView {
id: socialView
gameNetworkItem: gameNetwork
multiplayerItem: multiplayer
visible: false // we show the view pages on our custom app navigation
}
}
See here for more information: https://v-play.net/cross-platform-app-development/how-to-add-chat-service-and-cross-platform-leaderboard-with-user-profiles-to-your-ios-or-android-app#add-leaderboard-with-user-profiles

Resources