How to have QML settings persistent for the application's lifetime - qt

I'm trying to create warning dialog that has a "Do not prompt again" option. However, because it's part of a stack view the dialog gets destroyed regularly, and it's properties get destroyed too. How do I create settings that are persistent for the life of the application, but get reset back to a default value when the application gets started?
Item {
Button {
id: backButton
text: "Go Back"
// todo: Figure out how to set this just once at the start of the application
property bool promptOnClick: true
onClicked: promptOnClick ? cautionDialog.open() : stackView.pop()
}
Dialog {
id: cautionDialog
title: "Caution"
standardButtons: StandardButton.Ok | StandardButton.Cancel
onAccepted: {
if (checkboxDisablePrompt.checked) {
backButton.promptOnClick = false
}
stackView.pop()
}
Row {
CheckBox {
id: checkboxDisablePrompt
checked: false
anchors.verticalCenter: parent.verticalCenter
}
Label {
text: "Do not prompt again"
anchors.verticalCenter: parent.verticalCenter
}
}
}
}

If I'm understanding correctly, you want property values in the dialog to persist for the duration of the application.
A good option would be to write these as properties in item. The you can bind the correct properties in dialog to the ones you just created in item. Whenever you want to edit the property, edit it in the item.
Whenever the dialog is created, it will use the current values of the properties in item that it is bound too.

Related

QML Dynamic Load Window On Button Press, But Focus Instead If Exists

I have a button within my main ApplicationWindow (root) that dynamically loads and opens a second, different ApplicationWindow that is declared in a separate .qml file.
Button {
id: btnLogger
text: "Logger"
onClicked: {
var component = Qt.createComponent("logger.qml")
var window = component.createObject(logRoot)
window.show()
}
}
This works fine for opening a window when clicking the button. Subsequent clicks create further new windows.
My intent is that subsequent clicks should instead focus the preexisting window. If the new window is later closed, then clicking the button should revert back to opening the window.
i.e. if a window doesn't currently exist or exists but has been closed, create it and open it; else, focus it.
How would this be done from within qml? Alternatively, I am currently loading the application from a QQmlApplicationEngine in my C++, how could I use that to achieve this functionality?
The example code for my comment above:
Button {
id: btnLogger
text: "Logger"
property var wnd: undefined
onClicked: {
if(wnd == undefined)
{
var component = Qt.createComponent("logger.qml")
wnd = component.createObject(logRoot);
wnd.closing.connect(function() { btnLogger.wnd = undefined;});
wnd.show();
}
else
{
wnd.requestActivate();
}
}
}

Qml ComboBox with TextField in Popup

I have created a custom ComboBox that uses a ListView with a TextField in the footer, that's used to dynamically add options to the ComboBox.
The problem is, that as soon as the popup loses focus (so when the TextField receives focus), the popup gets closed.
I tried to force the popup to stay open, which does work, but then prevents the TextField from receiving focus (I guess because the popup regains focus as soon as open() is called).
ComboBox {
// ...
popup: Popup {
property bool forceOpen: false
onClosed: {
if(forceOpen)
open()
}
contentItem: ListView {
// ...
footer: TextField {
onPressed: forceOpen = true
}
}
}
}
I also tried all values for the closePolicy property of the Popup, but none of them helped.
I am using Qt5.11. The forceOpen solution used to work with Qt 5.10, but does not anymore.
Your problem should be fixed if you do not accept the focus on the ComboBox:
ComboBox {
focusPolicy: Qt.NoFocus
popup: Popup {
// ...
}
}

Accessing members of ListView delegate which is loaded by Loader

ListView {
id: listView
model: someModel {}
delegate: Loader {
id: delegateLoader
source: {
var where;
if(model.type === 1) {
where = "RadioQuestion.qml";
}
else
where = "TextQuestion.qml";
if(delegateLoader.status == Loader.Ready) {
delegateLoader.item.question= model.question;
}
return Qt.resolvedUrl(where);
}
}
I show some questions to user by using ListView. But I cannot access members of delegate loaded by Loader.
RadioQuestion.qml has Radio Buttons and Text is just text field. I just want to get all answers after pressing a submit button but I could not figure out how I can traverse among delegates.
Maybe my approach is wrong about building this structure. Therefore I am open for better solutions.
Your question is already exposed through the model, so your delegates should directly bind to it, so assuming that question is a property of the model:
// from inside the delegate
question: delegateRootId.ListView.view.model.question
or assuming that question is a list element role:
// from inside the delegate
question: model.question
And if you were careful enough not to name the property inside the delegate question thus shadowing the model role, you could simply:
// from inside the delegate
questionSource: question
Not to mention that if your model "scheme" is known and it is a given that you will have a question role and that role will be displayed in the delegate, you don't even need any additional property in the delegate to begin with, you can bind the actual item directly to the question, for example:
// from inside the delegate
Text { text: question }
And that's all that's really needed.
Alternatively you can use a Binding or a Connections element or a simple signal handler to delay the operation until the loader has actually completed the loading. For example:
delegate: Loader {
source: Qt.resolvedUrl(model.type === 1 ? "RadioQuestion.qml" : "TextQuestion.qml")
onStatusChanged: if (status === Loader.Ready) if (item) item.question= model.question
}
Button {
text: "Submit answers"
onClicked: {
for(var child in listView.contentItem.children) {
var c = listView.contentItem.children[child].item;
if(typeof c !== "undefined")
console.log(c.answer)
}
}
}
You can get properties of loader delegate like this. We use "undefined" check, because one object in children of contentItem is undefined. That was second object in the list, I do not know why.

"Bind" two QML CheckBoxes together, ensuring their states are always identical

I'd like to create two checkboxes on different pages of a GUI such that they are semantically the "same" checkbox -- same label, same effect. (Having them on both pages is just for the user's convenience.)
This requires "binding" two CheckBox QML elements together such that the state of one is always reflected by the other, and vice-versa.
This is equivalent to what's being asked here, except I'm using QML/JS instead of JS/JQuery.
I thought that a naive implementation of binding the checked state of each checkbox to some global persistent property would work:
// Global shared state object
pragma Singleton
MySharedState {
my_feature_on: false
}
Then, on two separate pages, the exact same CheckBox instantiation:
// Checkbox implementation (on both pages
CheckBox {
checked: MySharedState.my_feature_on
onClicked: MySharedState.my_feature_on = checked
}
However, this doesn't work, because when a checkbox is clicked, it breaks the initial checked binding. This is the intended behavior, not a bug.
So how can I ensure that two checkboxes always share the same "checked" state?
EDIT: According to a comment bellow, the above implementation will work without modification in Qt Quick Controls 2, which was released with Qt 5.7, so this question only applies to prior versions of Qt (including 5.6, which is a "long-term support" release).
When a checkbox is clicked its' checked property is changed and the original checked: MySharedState.my_feature_on binding is removed.
You need to create a property binding from Javascript to restore the original binding as explained by J-P Nurmi in the bug report you linked.
For that you have to use Qt.binding().
CheckBox {
checked: MySharedState.my_feature_on
onClicked: { // the checked binding is removed since checked has been changed externally to the binding
MySharedState.my_feature_on = checked
checked = Qt.binding(function() {return MySharedState.my_feature_on}); //we restore the checked binding
}
}
Using a two-way binding with the Binding type works:
import QtQuick 2.5
import QtQuick.Controls 1.0
ApplicationWindow {
objectName: "window"
width: 600
height: 200
visible: true
Row {
CheckBox {
id: checkBox1
text: "Check Box 1"
}
CheckBox {
id: checkBox2
text: "Check Box 2"
}
}
Binding {
target: checkBox2
property: "checked"
value: checkBox1.checked
}
Binding {
target: checkBox1
property: "checked"
value: checkBox2.checked
}
}
Although I'm not sure why it doesn't complain about a binding loop.

How to know when the selected item has been changed in a QML QListView?

I'm using QtQuick 2.0 and and a QML ListView to display some items, and I need to know when the user chooses a different item. Emitting a signal when the user clicks a mouse area in the delegate works, i.e.
MouseArea{
onClicked: {
controller.itemChanged(model.item);
someList.currentIndex = index;
}
}
but only if the user uses the mouse to choose the item, but it doesn't work if the user uses the arrow keys.
I've been looking through the docs to find what signal is emitted when the currentIndex is changed, but I can't seem to find any. I'm looking for something similar to QListWidget::itemSelectionChanged() but it seems QML ListView doesn't have that.
You just need onCurrentItemChanged:{} in your ListView.
I ended up having to re-implement keyboard behaviour and exposing the model data from the delegate so I could fire the signal when a key is pressed.
ListView {
id: myList
focus: true
orientation: "Horizontal" //This is a horizontal list
signal itemChanged(var item)
interactive: false //Disable interactive so we can re-implement key behaviour
Keys.onPressed: {
if (event.key == Qt.Key_Left){
myList.decrementCurrentIndex(); //Change the current list selection
itemChanged(myList.currentItem.selectedItem.data); //Fire signal notifying that the selectedItem has changed
}
else if (event.key == Qt.Key_Right){
myList.incrementCurrentIndex(); //Change the current list selection
itemChanged(myList.currentItem.selectedItem.data); //Fire signal notifying that the selectedItem has changed
}
}
delegate: Component {
Rectangle {
id: myItem
property variant selectedItem: model //expose the model object
MouseArea {
anchors.fill: parent
onClicked: {
myList.currentIndex = index; //Change the current selected item to the clicked item
itemChanged(model.data); //Fire signal notifying that the selectedItem has changed
}
}
}
}
}
With this solution you have to manually change the item in QML whenever the user clicks an item or presses a key. I'm not sure this'd be an optimal solution with GridView but it works fine with ListView.
See this question. There are two approaches you can take
Connect to another component's event
Handle the event within that component
The signal handler is named on<SignalName> with the first letter of the signal in uppercase.

Resources