ListView model function - qt

I am just getting started in Qt, and trying to make function which operates ListView model's elements.
I have custom made button in "myButton.qml" which has states like "normal", "pressed", "selected", etc.
ListView is in "main.qml". Structure is like this:
ListView{
//...
model: nameModel
delegate: myButton {
//...
}
}
So here is my goal: this list of buttons should act like group of radiobuttons - only one can have selected state and selected state is when you press button. I think that I should have click handler and a function that calls on button click. Function should check the list of buttons and if one button was selected before function just changes its state to "Normal".
So I have no idea of how to write this func and where should I place it. I read Qt docs but still no idea.

A possible easy way to solve this problem is by exploiting ExclusiveGroup. As discussed in the documentation, support to this type can be added to any type:
It is possible to add support for ExclusiveGroup for an object or control. It should have a checked property, and either a checkedChanged, toggled(), or toggled(bool) signal. It also needs to be bound with ExclusiveGroup::bindCheckable() when its ExclusiveGroup typed property is set.
You can define an ExclusiveGroup at the ListView level and implement the required logic in the ListView delegate. By binding the delegate ExclusiveGroup property to the ExclusiveGroup of the ListView you should achieve what you want, without the need of a function that crawls the model.
Final toy example to demonstrate the usage:
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
id: root
visible: true
width: 200
height: 500
ListView {
anchors.fill: parent
model: 10
spacing: 20
ExclusiveGroup { id: ex } // the group for all the delegate
delegate: Rectangle {
id: delegate
width: ListView.view.width
height: 30
color: checked ? "yellow" : "steelblue"
// code to have exclusive behaviour
property bool checked: false
property ExclusiveGroup exclusiveGroup: ex
onExclusiveGroupChanged: {
if (exclusiveGroup)
exclusiveGroup.bindCheckable(delegate)
}
// mouse area to trigger the property change
MouseArea {
anchors.fill: parent
onClicked: checked = true
}
}
}
}

Related

Qt5-QML: How to handle change of color and text of a button after click event

I am writing a small application that is working as follows:
1) I launch the application and I select a robot to which I will connect. See print screen below of the small app:
2) That will lead me to another page where I can actually choose the robot to connect to as shown in the print screen below:
3) Finally after selecting the robot the application brings me back to the initial screen that will show me an additional Button showing the chosen robot.
The problem: I have is that after I choose the robot and I am back to the initial screen and I push the button the color of the button should turn into a (for example) green color and changing the text into (for example) Connecting...
The code I am using is the following for which I am only putting the related part:
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls.Styles 1.4
Page {
property int dialogId: -1
signal selectDialog()
ColumnLayout {
anchors.fill: parent
spacing: 5
Button {
id: button1
text: "Select Robot"
onClicked: selectDialog()
Layout.fillWidth: true
font.pointSize: 20
}
Button {
id: dialogA
text: "FreddieMercury: Connect";
visible: dialogId === 1
Layout.fillWidth: true
font.pointSize: 20
function buttonClick()
{
console.log("Button "+ dialogA.text +" is clicked!")
}
Rectangle {
id: button
color: "red"
width: 96; height: 24; anchors.centerIn: parent
MouseArea {
id: region
anchors.fill: parent;
onClicked: console.log("clicked()")
onPressed: dialogA.color = "green"
onReleased: dialogA.color = "red"
}
Text {
id: st_text
anchors.centerIn: parent
text: "Connecting..."
font.bold: true
font.pointSize: 20
color: "green"
}
}
}
// Other Buttons
}
}
What I tried so far
I went through this source and also this post which I followed. As you can see from the point 3) I am close to the good functioning but there is clearly something I am not doing right.
Also this was useful and in fact I used the MouseArea option exactly from that post.
However I still don't see the whole color extended into the button.
Finally the text changed after the click event happened I included it in the Button as shown and thought that the property text: "Connecting..." was enough to overwrite the existing text but without success.
Please advise on what I am missing that is keeping me from a full working example.
I think the base issue is that you're trying to use examples for QtQuick Controls 1 with QtQuick Controls 2. They're completely different animals and you cannot style the v2 controls using QtQuick.Controls.Styles.
For customizing Controls 2 styles, like Button, see here. I also find it useful to look at the source code for the included controls (they're in your Qt library install folder inside /qml/QtQuick/Controls2/ directory). Though personally I find needing to re-create a whole new Button (or whatever) just to change a color or font is a bit much, especially if I want it to work across all the included QtQuick Controls2 Styles.
An alternative is to "hack" the properties of the built-in Control styles. This certainly has some drawbacks like if you want to be able to reset the control style back to default bindings, you'd have to save the original bindings and re-create them to reset the style. OTOH it beats creating customized controls for each style. YMMV.
Anyway here's an example of what i think you're looking for. This is based on our previous exercise with the buttons. :) Specifically, I just modified the Page1.qml code and the other 2 files are exactly the same as before. In this page I added buttonClick() handler and the Button::onClicked calls to trigger it from each button (and the button texts of course :).
Page1.qml
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls.impl 2.12 // for IconLabel
import QtQuick.Layouts 1.12
Page {
property int dialogId: -1;
signal selectDialog()
function buttonClick(button)
{
button.text = qsTr("Connecting to %1...").arg(button.text);
button.enabled = false; // prevent repeat clicks
// If Button has a background Rectangle object then we can set properties on it.
// note: `instanceof` was added in Qt 5.10
if (button.background && button.background instanceof Rectangle) {
button.background.color = "red"; // override style color
button.background.gradient = null; // some styles use a gradient
button.background.visible = true; // some styles may hide it in some situations
}
// Similar with the label element, IconLabel is used by all included QML styles.
if (button.contentItem && button.contentItem instanceof IconLabel) {
button.contentItem.color = "blue"; // override style color
button.contentItem.font.bold = true;
button.contentItem.font.pointSize = 20;
}
}
ColumnLayout {
anchors.fill: parent
spacing: 5
Button {
id: button1
text: "Select"
onClicked: selectDialog()
Layout.fillWidth: true
}
// These buttons should appear only after the user selects the choices on `Page2`
Button {
id: dialogA
text: "Freddie Mercury"
visible: dialogId === 1
Layout.fillWidth: true
onClicked: buttonClick(this)
}
Button {
id: dialogB
text: "David Gilmour"
visible: dialogId === 2
Layout.fillWidth: true
onClicked: buttonClick(this)
}
Button {
id: dialogC
text: "Mick Jagger"
visible: dialogId === 3
Layout.fillWidth: true
onClicked: buttonClick(this)
}
}
}
If you had a customized Button (like in the Qt docs example) then you could still do basically the same thing in buttonClick() but probably w/out worrying about the if (button.background ...) stuff (since you'd be sure your button has valid background/contentItem Items).
A better implementation of a "default" (Style-specific) Button but with custom colors/text properties would involve a subclass which uses Binding and/or Connections QML elements to control the properties and be able to reset them back to the current QtQuick Style defaults.

Add elements to a ListView inside another ListView

I need to insert elements in a ListView inside another ListView (via JS code inside my QML file) but when I try to access the inner ListView I get the error :
TypeError: Cannot call method 'insert' of undefined
Here is an example code to show my problem :
Item{
id:list
width: parent.width-210
height: parent.height
x:105
Component{
id:listDelegate
Item {
id:elem
height: 100
width: parent.width
Item{
id:titre_liste
height: 50
width: parent.width
Text{
anchors.left: parent.left
color:"white"
text:titre_txt
font.pixelSize: 25
font.bold: false
}
}
Item{
id:listInList
width: parent.width-100
height: parent.height
Component{
id:listInListDelegate
Item{
id:element_liste
height: parent.height
width: parent.width/5
Text{
anchors.left: parent.left
color:"white"
text:element_txt
font.pixelSize: 25
font.bold: true
}
}
}
ListView {
id: viewin
anchors.fill: parent
model: ListModel{
id:listModel_in
}
delegate: listInListDelegate
}
}
}
}
ListView {
id: viewglobal
anchors.fill: parent
model: ListModel{
id:listModel
}
delegate: listDelegate
}
}
And here is my JS code, at the end of the QML file :
function addItem(){
var i;
var numListe = -1;
var liste = "titre"
var item = "item"
for(i = 0;i<listModel.count;i++)
{
if(listModel.get(i).titre_txt === liste)
{
numListe = i;
}
}
if(numListe === -1)//if the list doesn't exist
{
listModel.append({titre_txt:liste});
numListe = listModel.count-1;
}
listModel.get(numListe).listModel_in.insert(0,{element_txt:item});
}
The error come from the last line of the JS code, when I try to insert a new element in the inner list. I verified that the value of "numListe" is 0 so it is not just a problem of wrong index.
How can I add elements to the inner list ?
There is a lot of stuff wrong with that code.
For starters - it is a mess, which is a very bad idea for someone who is obviously new at this stuff. Keep it clean - that's always a good idea regardless of your level of expertise.
listModel_in is an id and as such cannot be accessed outside of the delegate component.
That object however happens to be bound to the view's model property, so as long as the model doesn't change, you can access listModel_in via the model property. However, the view itself doesn't look like it is the delegate root object, so you have to interface it, for example by using an alias.
However, the inner model doesn't exist in the outer model, it only exists in the outer model's delegate item.
So you cannot possibly get it from listModel. You can get it from the viewglobal view, however ListView doesn't provide access by index. So you will have to set currentIndex for every index and use currentItem.
So it will look like this:
viewglobal.currentItem.modelAlias.insert(0,{element_txt:item});
But it should go without saying, you are putting data in the GUI layer, which is conceptually wrong. But it gets worse than conceptually wrong - you might not be aware of this, but ListView only creates items that it needs to show, meaning that it creates and destroys delegates as necessary. Meaning if your item falls out of view, it will be destroyed, and when it comes back into view, a new one will be created, and all the data you had in the model of the old delegate item will be lost. The view should never store data, just show it.
The inner model should be inside the outer model. However, last time I checked, QMLs ListModel didn't support model nesting, neither using declarative nor imperative syntax. If you want to nest models, I have provided a generic object model QML type you can use.

QML StackView push component with properties

In QML StackView docs it is mentioned that you can push item with properties like this:
stackView.push({item: someItem, properties: {fgcolor: "red", bgcolor: "blue"}})
Is there a way with which we can push component with properties? My components are basically wrappers of other .qml files for different views of my app, for example:
Component{
id: loginComponent
Login{}//The Login.qml file of my project
}
This is what I'm trying:
Main.qml
ApplicationWindow {
id: appWindow
visible: true
width: Screen.desktopAvailableWidth
height: Screen.desktopAvailableHeight
property alias stackv: stackv
property alias loginComponent: loginCom
StackView {
id: stackv
anchors.top: topHeader.bottom
anchors.topMargin: 10
anchors.bottom: parent.bottom
width: parent.width
focus: true
Component {
id: loginCom
Login {
anchors.fill: parent
}
}
}
}
In another QML file, which got pushed as a component to the stackview, I'm trying this on one of the button's onClick method:
onClicked: {
appWindow.stackv.push({item: appWindow.loginComponent})
}
I get popped with this error:
QML StackView: push: nothing to push
If I try this without the item property, it works. However, either way, I can't push properties.
In the documentation you linked to, the first sentence says:
An item pushed onto the StackView can be either an Item, a URL, a string containing a URL, or a Component.
So just pass a component:
stackView.push({item: loginComponent, properties: {/*...*/}})
EDIT: It turns out, after you have edited the question and added a warning output, that you are actually using StackView from Qt Quick Controls 2, not from Qt Quick Controls 1 where your documentation link points to.
QML StackView::push() (Qt Quick Controls 2)
stackView.push(loginComponent, {/*...*/})

Can I select text by mouse from a number of delegates in QML?

Lets imaging project for desktop which contains only one QML file:
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
width: 500
height: 500
ListModel {
id: myModel
ListElement {
color: "red"
text: "some interesting information"
}
ListElement {
color: "blue"
text: "not so interesting information"
}
ListElement {
color: "green"
text: "and some more information"
}
}
ListView {
anchors.fill: parent
interactive: false
model: myModel
delegate: Rectangle {
width: parent.width
height: 30
color: model.color
TextEdit {
anchors.centerIn: parent
text: model.text
selectByMouse: true
}
}
}
}
With the selectByMouse property of TextEdit set to true I can select text in it. But how can I select text in multiple delegates at the same time? In multiple TextEdits? Is it even possible?
Since the other answers seem incomplete or don't answer what I believe VALOD9 was asking: "can you select text across multiple delegates as though their TextEdits are one element?"
This is not inherently possible, but can be crafted in QML with a lot of manual tracking of mouse presses and movement.
It could be accomplished by placing MouseArea over your ListView and delegates that each contain DropAreas. To track your text selection clicks/drags across your delegates, you could use an invisible MouseArea.drag.target that triggers the delegate DropAreas' onEntered and onPositionChanged events. Based on all this data, you can use TextEdit.positionAt() with your mouse coordinate results to get where your selections start and end, and use TextEdit.select() to programmatically select the text in each delegate. Since you are programmatically selecting text, your TextEdits would need to have selectByMouse: false.
You will need to store any necessary selection data in your model since you shouldn't store state in delegates in case they are removed from the ListView from automatic caching. You would then use this data to recreate the selection when they are re-loaded from cache using Component.OnCompleted. To do selection operations like copy, you could iterate over your model and pick up the saved selection data (especially if you save the selected text to the model using TextEdit.selectedText).
This would allow many TextEdit-based delegates to act as though they are one when selecting text across any of them.
You can set persistentSelection to true and each of your TextEdit will keep the text selected (http://doc.qt.io/qt-5/qml-qtquick-textedit.html#persistentSelection-prop)

ListView signals and slots for menu elements

I'm trying to implement some sort of custom Menu with custom elements. The ultimate goal is to create some sort of popup menu with text and icons. But during creation I faced with some issues. I can show 2 primary problems:
There is a strange menu element with title Hello world at the first position (looks like it's read title of application window):
From time to time I'm getting errors like qrc:/BreezeQuickMenu.qml:45: TypeError: Property 'clicked' of object QQuickListView(0x1120830) is not a function
Here is my actual code:
main.qml
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.2
ApplicationWindow {
title: qsTr("Hello World")
width: Screen.width
height: Screen.height
visible: true
id: win
color: brPalette.normalBackground
BreezeQuickMenu{
id: brMenu
x: 490
y: 199
width: 128
height: 256
palette: brPalette
menuFont.pointSize: 16
BreezeQuickMenuItem{
title: "Item 1"
onClicked: mbox.show()
}
BreezeQuickMenuItem{
title: "Item 2"
}
BreezeQuickMenuItem{
title: "Item 3"
}
}
}
BreezeQuickMenu.qml
import QtQuick 2.4
Item {
id: root
property BreezeQuickPalette palette: BreezeQuickPalette
property alias currentIndex: menuList.currentIndex
property font menuFont
property bool menuVisible: false
implicitWidth: 128
implicitHeight: menuList.height
ListView{
id: menuList
anchors.fill: parent
model: root.children
clip: true
delegate: Component {
id: menuItem
Rectangle {
id: menuElement
property bool isCurrentItem: ListView.isCurrentItem
anchors {
left: parent.left
right: parent.right
}
color: palette.normalBackground
height: menuText.font.pixelSize*1.2
Text {
id: menuText
anchors.fill: parent
text: title
color: palette.normalText
font: menuFont
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onClicked: {
menuList.currentIndex = index
menuList.model[index].clicked()
}
}
}
}
}
}
BreezeQuickMenuItem.qml
import QtQuick 2.4
Item {
id: root
property string title: "Menu Element"
signal clicked
}
As you can see I'm trying to implement menu list and menu items with their own signals. I have 2 questions:
how can I properly get rid of using title property of parent element, since I need to read title property of childrens
what is the correct approach of using signals and slots in menu elements to avoid above error?
Please help me to understand. Full project can be pulled here:
git clone git://git.code.sf.net/p/breezequick/code breezequick-code
The problem with the signal is related to its declaration. Signals are always declared as a function would be: with a signature. In other words, a signal without parameters has the form
signal <signal_name>()
That's also why you got the error "is not a function". Apart from that, the usage of signals/signal handlers is correct. Anyhow, reading carefully the documentation wouldn't hurt. This page covers in detail the argument.
Coming to the other problem, you made the wrong assumption: anything that is declared inside a component is part of the children of the component itself. Here you declared a BreezeQuickMenu which has a child ListView. When you use it and add the BreezeQuickMenuItems, you add them to the same set to which the ListView belongs. In the end you have four elements in the children property. Also, by adding the ListView to itself through the model you mess up things to the point that a totally unrelated string is rendered.
There are several ways to handle Items as model members for a view, inclusing VisualItemModel and using object Instanced as models. However, by skimming your code, it is clear that you want to define a component which adds menu items in a declarative fashion. Using children is not sufficient in this case. You also need the default property:
An object definition can have a single default property. A default property is the property to which a value is assigned if an object is declared within another object's definition without declaring it as a value for a particular property.
Hence you can define the default property for your BreezeQuickMenu and exploit it to obtain the desired children for your list. A common approach would be the following (code simplified):
import QtQuick 2.4
Item {
id: root
property BreezeQuickPalette palette: BreezeQuickPalette
property alias currentIndex: menuList.currentIndex
// default declaration (1)
default property alias contents: addItem.children
// Item to which the inner declared meantime will belong (2)
Item {
id: addItem
}
property font menuFont
property bool menuVisible: false
implicitWidth: 128
implicitHeight: menuList.height
ListView{
id: menuList
anchors.fill: parent
model: contents // usage of the default property (3)
clip: true
delegate: Rectangle {
// your current delegate code
}
}
}
The basic idea is to exploit also property alias: basically in (1) we are saying that "all the Items declared inside BreezeQuickMenu are automatically children of addItem which is an inner declared Item (2). In this way the ListView is kept apart whereas all the BreezeQuickMenuItem are gathered together, under addItem children property. At this point, it is sufficient to use the same children property as the model (3) for the ListView and that's it.

Resources