Qt/QML: How to refer to a component/object from a GridView's model's ListElement - qt

I have a GridView with a delegate that is supposed to use a Loader to load and display components which are defined in the same QML file.
Let's say I have a GridView like this:
GridView {
delegate: Rectangle {
Loader { sourceComponent: model.pageContents }
}
model: ListModel {
ListElement { /* how do I reference any of the components defined below from here, so the Loader can actually load and display it... ? */ }
}
}
Component {
id: page_01
Rectangle {
color: "red"
// Page contents for page 1 go here.
}
}
Component {
id: page_02
Rectangle {
color: "red"
// Page contents for page 2 go here.
}
}
I know I can create QML objects and components from Strings, external files and URLs. But I'd like to ideally do something like this:
ListModel {
ListElement { pageContents: page_01 }
ListElement { pageContents: page_02 }
}
I'd prefer to keep everything in a single QML file, so I can easily transfer and store it on the device without having to worry about resolving external dependencies, etc.
How do I refer to components in the same QML file from within ListElements?

Due to ListElement values limitation you cannot just put item id here. But you easily can use some external storage, for example property to store pointers to your pages. In example below I use array with pages ids and an index to wanted page as ListElement data:
import QtQuick 2.3
import QtQuick.Window 2.2
Window {
visible: true
width: 600
height: 600
GridView {
id: grid
anchors.fill: parent
property var pages: [page_01, page_02]
model: ListModel {
ListElement { pageIndex: 0 }
ListElement { pageIndex: 1 }
}
delegate: Loader { sourceComponent: grid.pages[pageIndex] }
}
Component {
id: page_01
Rectangle {
color: "red"
width: 100
height: 100
Component.onCompleted: console.log("page_01 was created")
}
}
Component {
id: page_02
Rectangle {
color: "blue"
width: 100
height: 100
Component.onCompleted: console.log("page_02 was created")
}
}
}

Related

How to dynamically append elements to ListModel from exterior scope

Suppose I had the Component
Component {
id: myComp1
Item {
id: item
ListView {
id: listView
model : ListModel { id: listModel }
delegate : RowLayout { /* display model data*/ }
Component.onCompleted {
// get data from server ...
model.append(dataFromServer)
}
}
}
}
Then I have a second Component, which is another page in the stack, and I want to use this component to update mycomp1, i.e:
Component {
id: myComp2
Button {
onClicked: {
myComp1.item.listView.listModel.append(someNewData) // want to be able to do this
}
}
}
And these components are tied together in a StackView
Now, this doesnt seem to work since myComp2 cant seem to access the necessary scope to update the model of myComp1. Is there any way around this?
Thanks for the help.
The problem is that a Component is like a type declaration. It does not define an instance of an object, so you cannot access its members.
You could pull the ListModel outside of that Component so that both Components can access it.
ListModel {
id: listModel
}
Component {
id: comp1
ListView { model: listModel }
}
Component {
id: comp2
Button {
onClicked: { listModel.append(someNewData) }
}
}

Qt.createComponent url of the library components

Below is a function from TimelinePresenter.qml which is a custom component I created.
function createMenu() {
var menuComp = Qt.createComponent("Menu.qml");
if( menuComp.status != Component.Ready )
{
if( menuComp.status == Component.Error )
console.debug("Error: " + menuComp.errorString());
return;
}
}
It gives the error:
Error: qrc:/qml/timeline/Menu.qml:-1 No such file or directory
TimelinePresenter.qml is a resource file specified in the .qrc file and its path is qml/timeline as shown in error message so qml engine is trying to find the Menu.qml there expectedly. How can I specify the path to create qt's Menu component?
Edit:
my resources.qrc file
<RCC>
<qresource prefix="/">
<file>qml/main_window.qml</file>
<file>qml/timeline/TimelineViewItem.qml</file>
<file>qml/timeline/HorizontalLine.qml</file>
<file>qml/timeline/TimelineView.qml</file>
<file>qml/timeline/VerticalLine.qml</file>
<file>qml/timeline/timeline-item/timeline_item.h</file>
<file>qml/timeline/TimelinePresenter.qml</file>
<file>qml/timeline/timeline-item/analog_timeline_item.h</file>
<file>qml/timeline/timeline-item/digital_timeline_item.h</file>
<file>qml/timeline/timeline_presenter_backend.h</file>
<file>qml/ControllableListPresenter.qml</file>
<file>qml/controllable_list_backend.h</file>
<file>qml/controllable-popup/AddControlUnitPopup.qml</file>
<file>qml/styled/CenteredPopup.qml</file>
<file>qml/styled/StyledTextField.qml</file>
</qresource>
</RCC>
You are confusing the creation of a component with the creation of an object that belongs to a component.
The Menu component already exists and is provided by Qt, what you must do is create the object using the Qt.createQmlObject() method.
Example:
var menuObj = Qt.createQmlObject('import QtQuick.Controls 2.0 ; Menu {
MenuItem { text: "Cut" }
MenuItem { text: "Copy" }
MenuItem { text: "Paste" } }', parentItem, "dynamicSnippet1");
Complete Example:
import QtQuick 2.7
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
id: parentItem
Component.onCompleted: {
var menu = Qt.createQmlObject('import QtQuick.Controls 2.0 ; Menu {
MenuItem { text: "Cut" }
MenuItem { text: "Copy" }
MenuItem { text: "Paste" }
}', parentItem,"dynamicSnippet1");
// test: open menu
menu.open()
}
}
In the case you have described in your comments, I would suggest to only create one Menu and only popup() it at the place where you have clicked, setting it in a specific context.
I prepared a small example to illustrate how the Menu could be used:
import QtQuick 2.7
import QtQuick.Window 2.0
import QtQuick.Controls 2.3 // Necessary for the "Action" I used. Create the Menu otherwise if you are bound to older versions.
import QtQml 2.0
ApplicationWindow {
id: window
visible: true
width: 600
height: 600
Repeater {
model: ListModel {
ListElement { color: 'black'; x: 400; y: 50 }
ListElement { color: 'black'; x: 100; y: 190 }
ListElement { color: 'black'; x: 70; y: 80 }
ListElement { color: 'black'; x: 30; y: 0 }
ListElement { color: 'black'; x: 340; y: 500 }
ListElement { color: 'black'; x: 210; y: 10 }
}
delegate: MouseArea {
x: model.x
y: model.y
width: 50
height: 50
property QtObject modelItem: model
onClicked: menu.openMenu(x + mouse.x, y + mouse.y, modelItem)
Rectangle {
color: model.color
anchors.fill: parent
}
}
}
Menu {
id: menu
Action { text: "green" ; onTriggered: { menu.currentContext.color = text } }
Action { text: "blue" ; onTriggered: { menu.currentContext.color = text } }
Action { text: "pink" ; onTriggered: { menu.currentContext.color = text } }
Action { text: "yellow" ; onTriggered: { menu.currentContext.color = text } }
Action { text: "orchid" ; onTriggered: { menu.currentContext.color = text } }
Action { text: "orange" ; onTriggered: { menu.currentContext.color = text } }
Action { text: "teal" ; onTriggered: { menu.currentContext.color = text } }
Action { text: "steelblue"; onTriggered: { menu.currentContext.color = text } }
property QtObject currentContext
function openMenu(x, y, context) {
currentContext = context
popup(x, y)
}
}
}
Though I think this answer might solve your problem, I know that it is not really the answer to the question you stated initially.
For the Component-part: I think you misunderstood what a Component is - it is not an Item. It is a prestage in the creation of QtObjects and more something like a prototype or configured factory.
So your function - if it would work - would end at the creation of a invisible thing, from which you could create objects, by calling createObject().
Creating Components is the right thing to do, if you want to create an object at a later time and you might want to create similar objects multiple times, either by JavaScript or by other QML-types that expect Components as some input (e.g. delegates).
To create Components you have multiple possibilities, e.g.:
Qt.createComponent(url)
Component { SomeItem {} }
The first expects you to know the url, which in your case, you do not. To circumvent that, the easiest solution is, to create a new File, like MyMenu.qml
that only contains the Menu {} - then you can create a Component from this.
The second does not expects you to know the url, but it is not dynamically created.
Component {
id: myCmp
Menu {
}
}
onSomeSignal: myCmp.createObject({ prop1: val1 }, this)
Here the Component is automatically created when the object in the file is instantiated. This makes that (one time) initially a bit slower, since more code has to be processed, but you don't have to do it later.
Creating objects like eyllanesc shows with Qt.createQmlObject("Write a new QML-File here") might be also used to create a Component if the top-level element is a Component. If you don't have a Component as top-level, it will also first create a component that is once used to create a QtObject and then is discarded. It is the slowest but most flexible way to dynamically create objects.

Create QML Items out of DelegateModel

Is it possible to create QML Items out of a DelegateModel?
Here is a example DelegateModel:
DelegateModel
{
id: delegateModel
model: ListModel
{
ListElement { name: "#FAFAFA"; test: "object1" }
ListElement { name: "#000000"; test: "object2" }
}
delegate: Rectangle
{
objectName: test
width: 50
height: 50
color: name
}
Component.onCompleted:
{
Utils.var_dump(items,3)
items.create(0)
Utils.var_dump(items.get(0),3)
}
}
The Result should look like this:
Rectangle
{
objectName: "object1"
width: 50
height: 50
color: "#FAFAFA"
}
Rectangle
{
objectName: "object2"
width: 50
height: 50
color: "#000000"
}
For every ListElement there is a created delegate with the inserted ListElement data.
You can do that with anything that is usable to instantiate a Model (a View)
For example you could use it as a model for a ListView, a GridView or a Repeater. As the model provides the delegate on its own, you do not need to specify any delegate in the View, that instantiates it.
Column {
Repeater {
model: delegateModel
// delegate: ... <--- Nothing here! Uses the delegate from the Model.
}
}
If you use the create(index)-Method, the delegate will be created, but has no parent, so it is not displayed. So you need to set the parent, to have it shown:
Button {
onClicked: {
for (var a = 0; a < dm.items.count; a++) {
var o = dm.items.create(a)
o.parent = r
}
}
}
You need to be aware, that the DelegateModel (without Package and Parts) can't be used in multiple views, as each entry/delegate can be instantiated only once at the same time. If you want to have that,
consider using a QSortFilterProxyModel to filter the stuff, and use as much Views that provide their own delegates, as you want.

Access ListView model within the Repeater component in the delegate

I am using a ListView with a model and a delegate.
The model is a simple ListModel with three items. Each item has a value with the key myFirstRole.
The delegate contains a Repeater component to create an arbitrary number of Labels. The Labels have to use data from the model.
The model of the repeater can not be set to the Listview's model as I have the Repeater using other data.
Here is a minimal example of what I am trying to achieve:
//MyDelegate.qml
Component {
Item {
id: root
width: childrenRect.width
height childrenRect.height
Repeater {
model: 5 //It's not an option to set the repeaters model to the ListViews model. This example just illustrates my problem.
Label {
text: root.ListView.view.model.myFirstRole //This is the line where I want to be able to access the ListView's model, but I can't figure out how to properly reefer to it.
}
}
}
}
//MyListView.qml
ListView {
id: root
delegate: MyDelegate {}
model: ListModel {
ListElement {
myFirstRole: "one"
}
ListElement {
myFirstRole: "two"
}
ListElement {
myFirstRole: "three"
}
}
}
Using Qt 5.7.0 with MSVC2015 32bit
I think that you can't access the roles via the special model property mentioned here (which is what I'm assuming you were trying to do) from the scope of the Repeater. Instead, you can declare a property at the root level of the component that can then be used in nested scopes:
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
ListView {
anchors.fill: parent
model: ListModel {
ListElement { myFirstRole: "Dog" }
ListElement { myFirstRole: "Cat" }
}
delegate: Item {
id: root
width: childrenRect.width
height: childrenRect.height
property string myFirstRoleData: myFirstRole
Repeater {
model: 5
Text {
text: myFirstRoleData
}
}
}
}
}
This might get a bit tedious if you have a lot of properties though. From some quick playing around, it looks like it's also possible to store the entire model object in a property:
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
ListView {
anchors.fill: parent
model: ListModel {
ListElement { myFirstRole: "Dog" }
ListElement { myFirstRole: "Cat" }
}
delegate: Item {
id: root
width: childrenRect.width
height: childrenRect.height
property var modelData: model
Repeater {
model: 5
Text {
text: root.modelData.myFirstRole
}
}
}
}
}
modelData is probably not the best name to use though, seeing as Qt uses that name for models with only one role, but... if you're going with this approach, you're gonna have more than one role anyway. :)
It looks like Qt Quick Controls' (1) Tumbler does this too.
//MyDelegate.qml
Item {
id: root
property var listViewModel // pass the model data to here
width: 100
height: 50
Column {
Repeater {
model: 5 // Use a different model here
Text {
width: 50
height: 10
text: listViewModel.myFirstRole //This is the line where I want to be able to access the ListView's model, but I can't figure out how to properly reefer to it.
}
}
}
}
//MyListView.qml
ListView {
id: root
width: 100
height: 500
delegate: MyDelegate {
listViewModel: model // set the model data here
}
model: ListModel {
ListElement {
myFirstRole: "one"
}
ListElement {
myFirstRole: "two"
}
ListElement {
myFirstRole: "three"
}
}
}
See the comments in the code. It is not trivial to guess what you want to achive, but I hope I guessed right.

ListElements (ListModel) defined in other qml files?

I got a fonctionnal ListModel defined like this :
ListModel {
id: leftGrid
ListElement { icon: "Images/1.png" }
ListElement { icon: "Images/2.png" }
}
The thing is that I'd like to define ListElement in separate qml files but I really don't know how to do it...
I wrote the qml like this :
//myWidget.qml
import QtQuick 1.0
ListElement {
icon: "Images/X.png"
}
But I don't know how to "invoke" or "instanciate" it in my main file...
I tried :
ListModel {
id: leftGrid
ListElement { icon: "Images/1.png" }
myWidget //qml file
}
and :
ListModel {
id: leftGrid
ListElement { icon: "Images/1.png" }
ListElement { myWidget }
}
Both doesn't work...
Any help with be welcomed, thanks in advance.
I don't think it's possible to have ListElements as separate files. This is because when you do that you are implicitly creating a Component, with your contents inside (in this case the ListElement). However the ListModel can only accept ListElements as its children, not Components with nested ListElements inside.
What you can do however to dynamically define your model items is to declare a ListModel, then add your data via a piece of javascript, for example in your Component.onCompleted handler.
If you look at the API for ListModel you will see it has an append() method, among others.
You can pass a JS dictionary to this method and it will add a new ListElement to the list and populate its properties according to the dictionary.
Example:
import QtQuick 1.0
Rectangle {
width: 360
height: 360
ListView {
id:list
anchors.fill: parent
model: ListModel {
ListElement { foo: "hello" }
}
delegate: Text {
text: foo
width: ListView.view.width
}
Component.onCompleted: {
list.model.append({ "foo": "world" })
}
}
}
Your list will appear with two items in it: "hello" and "world"

Resources