Rotate multiple 'Text' messages in Qt Quick application - qt

My application has a message area that can fit only one Text item from the below code: But I wanted a logic to rotate the messages Text 1, Text 2 and Text 3 every one second. So that all the three messages can be displayed in my message area.
import QtQuick 2.3
Item {
id: root
width: 480
height: 320
Rectangle {
color: "#272822"
width: 480
height: 320
}
Column {
spacing: 20
Text {
text: 'Text 1'
visible: (timerCount == 1)
}
Text {
text: 'Text 2'
visible: (timerCount == 2)
}
Text {
text: 'Text 3'
visible: (timerCount == 3)
}
}
}
I am able to achieve this using a timer. To set visible property of Text items based on the timerCount.
property int timerCount = 0;
Timer {
id: onesecondtimer
interval: 1000
running: true
repeat: true
triggeredOnStart: true
onTriggered: {
if(++timerCount > 3)
timerCount=1;
}
It works fine, but am not happy with this approach since it gets more difficult if I want to maintain multiple messages (more than 3).
Am just wandering if QtQuick already supports something like this, which am not yet able to find. I tried searching Qt documentation for some time but was not able to find it.
Any help on this is appreciated. Thanks in advance.

Related

QML Scroll View does not allow scrolling of its content

I need to create components dynamically add added to an area of the screen that, of course, needs to be scrollable. I found out that no matter how many of components I added with the scroll bar as its parent, the scroll bars would not appear and the element would not be scrollable.
I did a little fiddling and I think I came up with a minum working example of what I am talking about:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ScrollView {
width: 200
height: 200
clip: true
Label {
text: "ABC"
font.pixelSize: 224
}
// Rectangle {
// color: "#ff0000"
// width: 100
// height: 100
// }
}
}
This is a modified version of the example used int he official documentation. However when I uncomment the square the screen is no longer scrollable (scroll bars never appear).
If I remove the label and leave the rectangle (making it larger so that there is something to scroll to) it still doesn't work.
I am using Qt 5.10.
So the code below worked for me. I defined a rectangle as a backgroud to get border lines to a scrollable table that I need to create.
Rectangle {
id: tableBackground
color: "#ffffff"
border.width: 2
border.color: "#EDEDEE"
radius: 4
anchors.top: tableHeader.bottom
anchors.left: tableHeader.left
width: vmTableWidth
height: vmTableHeight - tableHeader.height
ScrollView {
id: tableArea
anchors.fill: parent
clip: true
ListView {
id: patientListView
anchors.fill: parent
model: patientList
delegate: VMPatientEntry {
onFetchReport: {
// This is a signal emitted by my VMPatientEntry.
}
}
onCurrentIndexChanged: {
// Do stuff when the current index changes.
}
}
}
}
So I hope this answer allows someone to fix their problem as well.

Qt/QML - Positioner property not attaching to model delegate

I'm using Qt Creator 4.6 on Linux. My problem can be reduced to the setup that is essentially the example provided in the documentation with some small changes:
https://doc.qt.io/qt-5/qml-qtquick-positioner.html
If I run the below code it draws some boxes, and clicking on each box should output its index. The code below works correctly for me as written. However, if I comment out TEXT 1 and uncomment TEXT 2, then clicking on the boxes outputs -1 for every box.
It seems like I have to use the Positioner in some way before the MouseArea or it won't work correctly (it can be used in the Text item or you can use it at the Rectangle level). I'm guessing it has something to with the MouseArea not being fully resolved until the actual click, and maybe if the compiler feels like nothing uses the Positioner it doesn't create it?
Is this behavior expected, and if so is it documented anywhere? In my real use case the workaround is to just use the Positioner to assign an index to an unused property or variable at the parent level so it's not too big a deal, but I'd like to understand it.
Window {
visible: true
width: 640
height: 480
Grid {
Repeater {
model: 16
Rectangle {
id: rect
width: 30; height: 30
border.width: 1
//color: Positioner.isFirstItem ? "yellow" : "lightsteelblue"
color: "green"
Text {
text: rect.Positioner.index //TEXT 1
//text: "test" //TEXT 2
}
MouseArea {
id: dragArea
anchors.fill: parent
onPressed: {console.log(rect.Positioner.index)}
}
}
}
}
}

QML several items with active focus / keyboard shortcut control

I'm trying to implement a keyboard shortcut control for my qml application. I know there's the possibility to do that with an Action element, but I don't want menus and toolbars which are then mandatory to use.
That's why I'm approaching this topic with keyboard events. For this, I need to have the element performing the action to be in focus. But my goal is a global shortcut control, so theoratically I'd need to have all the elements in question in focus.
I found the FocusScope type in the documentation, but I'm not sure if this is what I need.
Does it mean that the focus of nested FocusScopes 'slides' through to the last element that's not a FocusScope and acquiring focus manually with focus: true thus only this last element holding focus? Or do all the elements on the way down the slide that acquire focus have the activeFocus property set?
Is this the right approach or would I need something else?
Focus in Qt Quick is a mess in my opinion. It always confuses me and I end up hacking around it with forceActiveFocus(). I'd recommend the new Shortcut type:
Shortcut {
sequence: StandardKey.Quit
context: Qt.ApplicationShortcut
onActivated: Qt.quit()
}
With the context property, you can choose whether you want the shortcut to apply to the current window or the entire application.
The motivation for this type can be seen in the comments of patch set 5:
Shortcut aims to supersede Action. I want to kill the latter in the future because...
compare the actual user code: http://cutebin.fi/prwznhkbo
look at the amount of "action" related expressions all around BasicButton.qml
IMHO the whole concept doesn't quite fit mobile/embedded or QML
Action was a frequently requested feature. Now that they have it, the frequent questions are "how to use a different icon/text" or "how to know the source that triggered an action". Both are contradicting the sole purpose of Action, and neither "problem" would exist if they just wrote simpler QML code in the first place, as illustrated by the example snippet. :)
Evidently the most usable part of Action is the shortcut feature. Those who need shortcuts are not happy that they need to use Action, because "what's up with all this other stuff, I just want a shortcut".
Maybe there are different ways of achieving this, but the way I know is the following one.
The idea is to have an Item which controls the key events you need to handle.
I'll explain myself with an example. As you will see, if we have input widgets (i.e. TextInput) we have to implement a mechanism to return the input to our Item in order to process again the keyboard events. In this example, the Qt.Key_Escape key will be used to set the focus back.
import QtQuick 2.4
import QtQuick.Controls 1.3
ApplicationWindow {
id: mainwindow
title: qsTr("Hello")
width: 640
height: 480
visible: true
Item {
anchors.fill: parent
focus: true
Keys.onPressed: {
if ( (event.key === Qt.Key_Q) && (event.modifiers & Qt.ShiftModifier) ) {
rect.blue()
} else if ( (event.key === Qt.Key_W) && (event.modifiers & Qt.AltModifier) ) {
rect.red()
} else if ( (event.key === Qt.Key_E) && (event.modifiers & Qt.AltModifier) ) {
text.text = 'Key Alt+E was pressed'
}
}
Rectangle{
id: rect
width: 100
height: 100
color: "black"
function blue() {color = "blue"}
function red() {color = "red"}
}
Text {
id: text
anchors.centerIn: parent
font.pointSize: 20
}
TextInput {
id: textinput
anchors.top: text.bottom
text: "sample text"
Keys.onPressed: {
if (event.key === Qt.Key_Escape) {
console.log('Key Escape was pressed');
parent.focus = true;
}
}
}
}
}
Edit #1: #Mitch suggested to use the Shortcut QML Type. If you can use it (it's available since Qt 5.5), the code will be slightly different. Anyway, you need also to set the focus to the main app in some cases depending on the shortcut sequences implemented. For example, if we're typing text, Shift+Q doesn't have effect in this example. We need to press Escape first.
import QtQuick 2.5
import QtQuick.Controls 1.3
ApplicationWindow {
id: mainwindow
title: qsTr("Hello")
width: 640
height: 480
visible: true
Shortcut {
sequence: "Shift+Q"
onActivated: rect.blue()
context: Qt.ApplicationShortcut
}
Shortcut {
sequence: "Alt+W"
onActivated: rect.red()
context: Qt.ApplicationShortcut
}
Shortcut {
sequence: "Alt+E"
onActivated: text.text = 'Key Alt+E was pressed'
context: Qt.ApplicationShortcut
}
Item {
anchors.fill: parent
Rectangle{
id: rect
width: 100
height: 100
color: "black"
function blue() {color = "blue"}
function red() {color = "red"}
}
Text {
id: text
anchors.centerIn: parent
font.pointSize: 20
}
TextInput {
id: textinput
anchors.top: text.bottom
text: "sample text"
Keys.onPressed: {
if (event.key === Qt.Key_Escape) {
console.log('Key Escape was pressed');
parent.focus = true;
}
}
}
}
}
Much like Mitch, I found focus to be a mess in QML, much like many other aspects of it.
I ended up implementing my own "active focus / selection" scheme. Basically I keep a list of item pointers as my "active selection", I have the keyboard focus fixed at a single item acting as an event dispatcher, and it redirects keyboard events to all items in the active selection list. I still use QML's MouseArea to manage the selected items.

How I can dropdown options when I check on checkbox?

I have one Checkbox with onCheckedChanged handler and what I want is, when the Checkbox is checked, dropdown a menu with several texts and text fields. I have the following code:
CheckBox {
id: box
onCheckedChanged: {
// TODO here to dropdown a menu with settings
}
}
I have texts and text fields like the following:
Component {
id: label
Text {
color: "red"
antialiasing: true
smooth: true
}
}
I'm a newbie in QML so please be patient.
You didn't really say where this menu is located, if it's floating or if it is to just appear maybe displacing other elements on the view. Anyway, to anwser your question, you can achieve what you're asking by setting the height of your 'menu' to zero then, when the CheckBox is checked, setting it to however tall you want it to be. To make the menu grow smoothing you can use a NumberAnimation.
You can change your onCheckedChanged() slot to look like this:
onCheckedChanged: {
menu.height = checked ? 100 : 0
}
and add the following, as a child of your menu element:
Behavior on height { NumberAnimation {...} }
to make the menu's height grow from 0 to 100 over a period of time to make it grow smoothly.
Another approach, which I'd prefer, is to use States with a Transition (instead of a Behavior).
Here is an example of a 'menu' which, when the CheckBox is checked, will slide out from beneath the CheckBox:
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
Rectangle {
id: checkboxContainer
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
height: 100
color: "pink"
CheckBox {
id: menuCheckBox
anchors.centerIn: parent
text: qsTr("Click Me")
}
}
Rectangle {
id: menu
anchors.top: checkboxContainer.bottom
anchors.left: parent.left
anchors.right: parent.right
height: 0 //This is the default value when the 'default' state is active. That is whenever we're not in the "openState"
clip: true // this hurts rendering performance a bit but is required to make sure child elements don't exceed the bounderies of this object (so when height is zero you don't see the text)
color: "lightblue"
states: [
State {
name: "openState"
when: menuCheckBox.checked // This state is only active when the check box is checked. When you uncheck the check box we move to the 'default' state (which sets the menu's hight back to zero)
PropertyChanges {
target: menu
height: 100
}
}
]
transitions: Transition {
NumberAnimation {
property: "height"
duration: 350 //This means when the height property is changed it will take 350ms to move from what its at to what your changing it to (i.e. 0 to 100 or 100 to 0).
easing.type: Easing.InOutQuad
}
}
Text {
anchors.centerIn: parent
color: "red"
antialiasing: true
smooth: true
text: qsTr("HELLO")
}
}
}
I hope this answers your question.

QML Keys.onEnterPressed issue

I have a QtQuick project for Desktop. It is very simple:
// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
Rectangle {
width: 360
height: 360
Grid
{
id: xGrid
width: parent.width
height: parent.height
columns: 2
spacing: 1
Rectangle
{
height: parent.height
width: 10
color: "#ff0000"
Text {
id: xText
text: qsTr("t\na\ns")
}
}
TextEdit
{
id: xTextEdit
height: parent.height
width: 350
Keys.onEnterPressed: {
console.log(event.key)
xText.text = (qsTr("A"))
}
}
}
}
My code does not run like I want. The Keys.onEnterPressed seem never be captured, so I try Keys.onPressed it work but not sure why when I press Enter, the even.key returns 16777220.
Any one get this issue? How can I solve it?
Thanks for your answer!
I got the same problem with a TextInput item. I tried
onPressed
onEnterPressed
onReturnPressed
Only the latter one worked (onReturnPressed). I guess, the underlying implementation of the TextInput captures the 'Enter' key so it doesn't get processed by the onPressed signal in a regular way.
By the way: the key code is correct. It's an abstraction on the platform specific key codes.
A better way to handle users entering a text value is to use TextInput.onAccepted
Here's an example:
TextInput {
onAccepted: processText()
}
When the user presses Enter, the processText() method will be called.
This approach is simpler and should improve cross-platform portability.
TextArea {
id: messageField
Layout.fillWidth: true
placeholderText: qsTr("Message")
wrapMode: TextArea.Wrap
inputMethodHints: Qt.ImhNoPredictiveText
function _onEnterPressed(event)
{
if ((event.modifiers & Qt.ControlModifier))
{
sendMessage()
}
else
{
event.accepted = false;
}
}
Keys.onReturnPressed: { _onEnterPressed(event) }
Keys.onEnterPressed: { _onEnterPressed(event) }
}
I'd say use onReturnPressed as well. Otherwise you can also check the key value in onPressed() and react there. onReturn/EnterPressed are just convenience functions.
Potentially relevant context taken from the docs:
[...] the order of key event
processing is:
Items specified in forwardTo
specific key handlers, e.g. onReturnPressed
onPressed, onReleased handlers
Item specific key handling, e.g. TextInput key handling
parent item

Resources