How to make some reusable QML object, which can inject another QML object? - qt

How to make some reusable QML object, which can inject another object?
I've ever tried to use Component & Loader , but seems not what I want. (It still encapsulate the whole QML type and lacks of elasticity, hard to reuse)
Usage example:
Card.qml
import QtQuick 2.0
import QtQuick.Layouts 1.3
Rectangle {
default property var innerObject
property string titleText: "[Hello Untitled Title]"
id: root
color: "#fff"
ColumnLayout {
anchors.fill: parent
Rectangle {
id: header
height: 10
width: parent.width
color: "#666"
RowLayout {
Text { text: titleText; color: "#fff" }
}
}
// How to inject innerObject in here ?
}
}
main.qml
import QtQuick 2.0
import QtQuick.Layouts 1.3
Card {
titleText: "Image Information"
ColumnLayout { /* .......*/ } // innerObject
}
Card {
titleText: "Image Viewer"
Rectangle { /* .......*/ } // innerObject
}

The answer I linked works like this:
Main.qml
Card {
titleText: "Image Viewer"
innerObject: Rectangle {
Component.onCompleted: {
console.log(parent.objectName)
}
}
}
Card.qml
Rectangle {
property string titleText: "[Hello Untitled Title]"
default property alias innerObject : innercolumn.children
id: root
color: "#fff"
ColumnLayout {
id: innercolumn
objectName: "column"
anchors.fill: parent
Rectangle {
id: header
height: 10
width: parent.width
color: "#666"
RowLayout {
Text { text: titleText; color: "#fff" }
}
}
}
}

I also want to suggest a solution based on default property and reparenting:
The Item which can embed another Item:
MyItem.qml
import QtQuick 2.7
import QtQuick.Layouts 1.2
Rectangle {
id: root
default property Item contentItem: null
border {
width: 1
color: "#999"
}
ColumnLayout {
anchors.fill: parent
Rectangle {
Layout.fillWidth: true
height: 30
color: "lightgreen"
}
Item {
id: container
Layout.fillWidth: true
Layout.fillHeight: true
}
}
onContentItemChanged: {
if(root.contentItem !== null)
root.contentItem.parent = container;
}
}
Can be used as below:
main.qml
import QtQuick 2.7
import QtQuick.Window 2.0
Window {
visible: true
width: 600
height: 600
MyItem{
width: 400
height: 400
anchors.centerIn: parent
Text {
text: "Hello!"
anchors.centerIn: parent
}
}
}
But I still agree with #ddriver that Loader is the best solution for this case

It is not mandatory that you use a Loader with a component. You can just go:
Loader {
source: "Something.qml"
}
When the source is something that can be loaded synchronously, you can directly use the loader's item for stuff like bindings, without worrying about whether or not it is created. If you load over network, you have to delay the bindings until the item is completed and use either a Binding element or Qt.binding() to do it respectively in a declarative or imperative manner.
In your case, a loader would be appropriate, and the property for the inner dynamic object outta be a Component. This way you can populate it either with an inline component, or with Qt.createComponent() from existing source.
property Component innerObject
...
innerObject: Component { stuff }
...
innerObject: Qt.CreateComponent(source)
Of course, there are even more advanced ways to do it, for example, the "generic QML model object" I have outlined here. It allows to quickly and easily create arbitrary data structure trees both declaratively and imperatively, and since the object is also a model, you can directly use listviews or positioner elements with repeaters to layout the gui without actually writing the UI code each and every time.
Also, from your main.qml code example - you cannot have more than one root element in a qml file.
Edit: The default property approach actually works if the element is moved to its own qml file, so also basically you could just:
default property alias innerObject: innerColumn.children
where innerColumn is the id of your ColumnLayout. Also, innerObject could be whatever legal name, since as a default property, it will not actually be used.
There is also the option to not use a default property, which is useful when the root item still needs to have its own children, but still have the ability to redirect declarative objects to be children of a sub-object:
property alias content: innerColumn.children
// and then
content: [ Obj1{}, Obj2{}, Obj3{} ] // will become children of innerColumn

Related

QML: Separators between list delegates

Has anyone found a good way to add separators between QML list delegates?
There is a very similar question here already but my problem is a bit more complex: How to set custom separator between items of ListView
Most of the time I use something similar as in an answer there:
ListView {
delegate: ItemDelegate {
...
Separator {
anchors { left: parent.left; bottom: parent.bottom; right: parent.right }
visible: index < ListView.View.count
}
}
}
However, depending on the design and backend data, I don't always have a ListView/Repeater at hand and need to add manual items in a ColumnLayout instead or a mix of some items from a repeater and some manual ones:
ColumnLayout {
ItemDelegate {
...
}
Separator {
Layout.fillWidth: true
}
ItemDelegate {
...
}
}
Now, both of those work but it's extremely annoying to always remember and type that separator. After lots of trying I still haven't been able to figure out a component that would take care of it.
The closest I've come to a custom Layout component like this (e.g ItemGroup.qml):
Item {
default property alias content: layout.data
ColumnLayout {
id: layout
}
Repeater {
model: layout.children
delegate: Separator {
parent: layout.children[index]
anchors { left: parent.left; bottom: parent.bottom; right: parent.right }
visible: index < layout.children.length
}
}
}
Now this works fine for manually adding items to such a group, but again it will not work in many corner cases. For instance putting a Repeater into such an ItemGroup will create a separator for the Repeater too (given it inherits Item and thus is included in children) which results in a visual glitch with one seemingly floating separator too much...
Anyone came up with a more clever solution for this?
I'd try this approach:
Make a custom component based on ColumnLayout.
Use default property ... syntax to capture children added to it into a separate list property.
Create a binding for the children property of ColumnLayout that interleaves each real child in your default property list with one of your Separators (using a Component to declare it and createObject() to create each one).
Here's a working example:
Separator.qml
import QtQuick 2.0
import QtQuick.Layouts 1.12
Rectangle {
Layout.fillWidth: true
height: 1
color: "red"
}
SeparatedColumnLayout.qml
import QtQuick 2.15
import QtQuick.Layouts 1.12
ColumnLayout {
id: layout
default property list<Item> actualChildren
property Component separatorComponent: Qt.createComponent("Separator.qml")
children: {
var result = [];
for(var i = 0;i < actualChildren.length;++i) {
result.push(actualChildren[i]);
if (i < actualChildren.length - 1) {
result.push(separatorComponent.createObject(layout));
}
}
return result;
}
}
main.qml:
import QtQuick 2.11
import QtQuick.Window 2.11
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.12
ApplicationWindow {
id: root
visible: true
width: 640
height: 480
title: qsTr("Hello World")
SeparatedColumnLayout {
anchors.fill: parent
Text {
Layout.alignment: Qt.AlignHCenter
text: "1"
}
Text {
Layout.alignment: Qt.AlignHCenter
text: "2"
}
Text {
Layout.alignment: Qt.AlignHCenter
text: "3"
}
}
}
The result:

QML: How to custom a component and use it in same file

Is there some syntax in QML to define and use a component in same file like this?
import QtQuick 2.6
import QtQuick.Window 2.2
var MyButton = Rectangle { width : 100; height : 60; color : "red" } // define it
Window {
visible: true
MyButton // use it
}
You can't really use an inline component directly, but you could use a loader:
Component {
id: btn
Button { width = 100; height = 60; background = "red" }
}
Loader {
sourceComponent: btn
}
Another downside is this way you cannot directly specify properties for the created object.
You can also use the component as a delegate for views and repeaters and such.
This is IMO one of the big omissions of QML.
Update: I just noticed this answer a bit out of date. Qt has had inline components for a while. Keep in mind they still have many bugs, there's stuff that will work in a regular component that will not work in an inlined one, especially around inline component properties in other inline components, property aliases and such. If you get some weird behavior, just remember to test it out standalone as well:
component Custom : Item { ...new stuff... }
... in the same source
Custom { }
Also note that it has to be put inside some qml object, it cannot be just a source code global as with JS files.
Powered by #dtech
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component { id: btn; Rectangle { width : 100; height : 100; color : "red" } }
Column {
spacing: 10
Loader { sourceComponent: btn }
Loader { sourceComponent: btn; width: 300 }
Loader { sourceComponent: btn; width: 1000 }
}
}
And the result:

How to setup my button component to open a window

Here is the code of the window I wanna be opened in file PopUpFreeCoins.qml:
import QtQuick 2.0
import QtQuick.Controls 2.1
Item {
property int t
property int c
ListModel{
id:ff
ListElement {
name: "ByFollow"
s: "Images/follow.png"
}
ListElement {
name: "ByLike"
s: "Images/care.png"
}
ListElement {
name: "ByComment"
s: "Images/chat.png"
}
}
ListView{
width:t-t/10
height: c/5
layoutDirection:Qt.LeftToRight
orientation: ListView.Horizontal
model: ff
spacing:50
delegate: Button{
contentItem: Image{
source: s
}}
}
}
property t is set equal to window width in main file and property c is set to window height. This is code of my Button.qml:
Button{//Below Right
width:profilePicture.width/2
height:profilePicture.width/2
x:profilePicture.x+profilePicture.width
y:profilePicture.y+profilePicture.height
contentItem: Image {
source: "Images/freecoins.png"
anchors.fill: parent
}
onClicked: PopUp{height:100;width:300;PopUpFreeCoins{t:a;c:b;}}
}
property a is window width and b is window height.
this line onClicked: PopUp{height:100;width:300;PopUpFreeCoins{t:a;c:b;}} has an error I don't know how to handle!
Here is the error:
Cannot assign object type PopUpFreeCoins_QMLTYPE_0 with no default
method
You need to create the Object somehow. You have multiple ways for dynamically create Objects. One way is to use Component.createObject(parent) which requires you to have a Component instantiated in your file.
Here you can also pass a Object ({property0 : value, property1:value ... }) as second argument, to set the properties of the Component to be instantiated. You should not set the parent to null as it might happen, that the JS-garbage collector is too aggressive once again.
Alternatively you can use the Loader to load it from either a source (QML-file) or sourceComponent. Here you won't have problems with the garbage collector.
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
width: 1024
height: 800
visible: true
Button {
text: 'create'
onClicked: test.createObject(this)
}
Button {
x: 200
text: 'load'
onClicked: loader.active = !loader.active
}
Loader {
id: loader
source: 'TestObj.qml'
active: false
}
Component {
id: test
TestObj {}
}
}
TestObj.qml includes the Window to be opened.
Alternatively you can have the Window created from the beginning, and just change the visible to true or false.

changing property of element from other qml file

I know that there is tons of topic similar like this, I try to implement answer from them and I still have no results.
I take some sample project from qt creator to play with this. I play with changing visibility of qml files ( treat every file as other screen). After lunching 3rd screen I want to make the second one invisible.
Here Is the code where I want change property in it:
MyLuncherList.qml
import QtQuick 2.0
Rectangle {
Item
{
id:ei
visible:false
clip: true
property url itemUrl
onItemUrlChanged:
{
visible = (itemUrl== '' ? false : true);
}
anchors.fill: parent
anchors.bottomMargin: 40
Rectangle
{
id:bg
anchors.fill: parent
color: "white"
}
MouseArea
{
anchors.fill: parent
enabled: ei.visible
//takes mouse events
}
Loader
{
focus:true
source: ei.itemUrl
anchors.fill: parent
}
}
}
and here is the code where I want to make a action
View2.qml
import QtQuick 2.0
Rectangle {
width: 100
height: 62
Text
{
text: "second screen"
}
MyLuncherList
{
id:luncherList
}
Rectangle
{
x: 50
y: 30
width: 120
height: 60
color: "red"
MouseArea
{
anchors.fill: parent
id: mouseAreaWhichHides
onClicked:
{
luncherList.ei.itemUrl = '';
}
}
}
}
and I got the error: qrc:///View2.qml:29: TypeError: Type error
which point on this line luncherList.ei.itemUrl = '';
Type error says that I make some mismatch with Type, but I’m not even sure, if I do this access process in properly way, so I’m asking how to change property of
ei.itemUrl
from
View2.qml
in working way.
The ei element won't be available directly in other QML file.
You can use an alias to do it.
property alias callUrl: ei.itemUrl
and call it from other QML file
luncherList.callUrl='file:///home/user/file.jpg'

Add elements dynamically to SplitView in QML

I am working with QML and I want to add elements to SplitView dynamically eg. onMouseClick, but so far I didn't find the answer.
What I've found out so far is that the SplitView has it's default property set to it's first child's data property. So I guess I should try and add new dynamically created components with the parent set to that child (splitView1.children[0]). Unfortunately that doesn't work either. What is more the number of children of that first child is zero after the component has finished loading (seems like the SplitLayout's Component.onCompleted event calls a function that moves those children somewhere else). Thus the added children do not render (and do not respond to any of the Layout attached properties).
Please see the following code snippet:
import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
ApplicationWindow {
width: 600
height: 400
SplitView {
anchors.fill: parent
Rectangle {
id: column
width: 200
Layout.minimumWidth: 100
Layout.maximumWidth: 300
color: "lightsteelblue"
}
SplitView {
id: splitView1
orientation: Qt.Vertical
Layout.fillWidth: true
Rectangle {
id: row1
height: 200
color: "lightblue"
Layout.minimumHeight: 1
}
// Rectangle { //I want to add Rectangle to splitView1 like this one, but dynamicly eg.onMouseClick
// color: "blue"
// }
}
}
MouseArea {
id: clickArea
anchors.fill: parent
onClicked: {
console.debug("clicked!")
console.debug("len: " + splitView1.__contents.length); // __contents is the SplitView's default property - an alias to the first child's data property
var newObject = Qt.createQmlObject('import QtQuick 2.1; Rectangle {color: "blue"}',
splitView1, "dynamicSnippet1"); //no effect
// var newObject = Qt.createQmlObject('import QtQuick 2.1; import QtQuick.Layouts 1.0; Rectangle {color: "blue"; width: 50; height: 50}',
// splitView1, "dynamicSnippet1"); //rectangle visible, but not in layout(?) - not resizeable
}
}
}
Is there any way I can make the dynamically created components render properly in the SplitView as the statically added ones?
It appears that the API does not provide support for dynamic insertion of new elements. Even if you do get it to work it would be a hack and might break with future releases. You may need to roll your own control to mimic the behavior you want. Ideally it should be backed by some sort of model.
As of QtQuick Controls 1.3, SplitView has an addItem(item) method.
you have to use the Loader for load dinamicaly objects. in onClicked handle you have to declare sourceComponent property to change the source of the Loader, something like this:
ApplicationWindow {
width: 600
height: 400
SplitView {
anchors.fill: parent
Rectangle {
id: column
width: 200
Layout.minimumWidth: 100
Layout.maximumWidth: 300
color: "lightsteelblue"
}
SplitView {
id: splitView1
orientation: Qt.Vertical
Layout.fillWidth: true
Rectangle {
id: row1
height: 200
color: "lightblue"
Layout.minimumHeight: 1
}
Loader {
id:rect
}
}
}
MouseArea {
id: clickArea
anchors.fill: parent
onClicked: {
console.debug("clicked!")
console.debug("len: " + splitView1.__contents.length) // __contents is the SplitView's default property - an alias to the first child's data property
rect.sourceComponent = algo
}
}
Component {
id:algo
Rectangle {
anchors.fill: parent
color: "blue"
}
}
}
I saw the source code of SplitView, it calculate each split region when Component.onCompleted signal. So I think that is a key point. No matter how you do (insert, dynamic create). The region won't be reset after you insert a new region for split.

Resources