QML animation - moving the application window - qt

I want to create an animation to move (or resize) my application Window built using QML.
I have the following code (most of it created by default when we create a QT quick Controls application:
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
MainForm.ui.qml
import QtQuick 2.6
import QtQuick.Controls 1.5
import QtQuick.Layouts 1.3
Item {
width: 640
height: 480
property alias button1: button1
property alias button2: button2
RowLayout {
anchors.centerIn: parent
Button {
id: button1
text: qsTr("Press Me 1")
}
Button {
id: button2
text: qsTr("Press Me 2")
}
}
}
main.qml
import QtQuick 2.6
import QtQuick.Controls 1.5
import QtQuick.Dialogs 1.2
ApplicationWindow {
id: mainWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")
flags: Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
menuBar: MenuBar {
Menu {
title: qsTr("File")
MenuItem {
text: qsTr("&Open")
onTriggered: console.log("Open action triggered");
}
MenuItem {
text: qsTr("Exit")
onTriggered: Qt.quit();
}
}
}
MainForm {
anchors.fill: parent
button1.onClicked: Qt.quit();
button2.onClicked: state = "other";
}
transitions: [
Transition {
from: "*"
to: "other"
NumberAnimation { properties: "x,y"; easing.type: Easing.InOutQuad; duration: 2000 }
}
]
states: [
State {
name: "other"
PropertyChanges {
target: mainWindow
x: x + 200
}
}
]
MessageDialog {
id: messageDialog
function show(caption) {
messageDialog.text = caption;
messageDialog.open();
}
}
}
With this code, I was simply trying to move my window 200 pixels to the right. When I try to run it, I get qrc:/main.qml:42 Cannot assign to non-existent property "states". I believe that is weird, because when I start typing "states" and choose to auto-complete, it builds to me the whole structure, so I thought it should exist...
I'm new to QML, and I'm not fully familiar with the several options of animations that exists. This one I've tried based on the example that comes with QT creator (animation.pro - code from transitions).
I believe it should be quite simple, right? Could you help me with this?

Qt Creator has a feature where you can insert code snippets using certain keywords. You can see which snippets are available by going to Tools > Options > Text Editor > Snippets.
Snippets will show up as red in the auto completion popup, and regular properties (or types, as is the case below) will show up as green:
So, ApplicationWindow doesn't have a states property. If you're ever in doubt, go to the documentation for the type you're interested in (e.g. http://doc.qt.io/qt-5/qml-qtquick-controls-applicationwindow.html) and click on the link that says "List of all members, including inherited members". This will show you all properties, functions, etc. belonging
to that type.
If you want to animate the window's position, you can use a NumberAnimation without using states:
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.5
ApplicationWindow {
id: window
width: 400
height: 400
visible: true
NumberAnimation {
id: xyAnimation
target: window
properties: "x,y"
easing.type: Easing.InOutQuad
duration: 2000
to: 500
}
Button {
text: "Start"
onClicked: xyAnimation.start()
}
}

state is a property in Item, however ApplicationWindow is not an Item. To add state/transition to an non-Item type, use StateGroup:
ApplicationWindow {
id: mainWindow
//your code...
MainForm {
button2.onClicked: { myWindowStates.state = "other";}
}
StateGroup {
id: myWindowStates
transitions: [
Transition {
from: "*"; to: "other"
NumberAnimation {
properties: "x,y"; easing.type: Easing.Linear;
duration: 2000
}
}
]
states: [
State {
name: "other"
PropertyChanges {
target: mainWindow
x: mainWindow.x + 200
explicit: true //Remember to set this
}
}
]
}
}
Remember to set PropertyChange.explict to true, otherwise the state behavior is wrong and your window will disappear after the transition finished.

Related

Qt seems to take only Mouse Events instead of touch screen, VirtualKeyboard Issue

I'm using debian 11, with a Xorg server running and Qt5.15.2 installed.
Very basic question that I don't know how to tackle: let's say we have a simple QML file with a InputPanel and a Textfield:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.VirtualKeyboard 2.15
import QtQuick.Controls 1.4
Window {
id: window
width: Screen.width
height: Screen.height
visible: true
title: qsTr("Hello World")
InputPanel {
id: inputPanel
z: 99
x: 0
y: window.height
width: window.width
states: State {
name: "visible"
when: inputPanel.active
PropertyChanges {
target: inputPanel
y: window.height - inputPanel.height
}
}
transitions: Transition {
from: ""
to: "visible"
reversible: true
ParallelAnimation {
NumberAnimation {
properties: "y"
duration: 250
easing.type: Easing.InOutQuad
}
}
}
}
TextField {
placeholderText: qsTr("Enter name")
}
}
I've already done in the main.cpp :
qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
And already inserted this line in the .pro file of my project:
QT += quick virtualkeyboard
The issue I found is: VirtualKeyboard does not type anything if I use the touch screen (it correctly appears but no key is prompted and warning "input method is not set" is raised), untill I click with my USB mouse. Then everything is fine, the virtual keyboard prompts and all is fine.
My question is: why? Is it something with X11, debian or something else(like xinput?)?
I tried some configuration of the Xserver for input handling, and adding focus to some QML elements but none works

Can't bind on current item in QML view/model

I have a simple task: need to output some information about current item of ListView separately. For example, in outside Label, but I can't succeed.
I figured out that problem related to where model was defined. If it is separate object with id this behavior happened. But when I define it inlined inside the view, all works fine. This behaviour is very weird and looks like a bug.
To make this code work, just switch to commented model definition. Anybody encounter this problem or may be know something?
import QtQuick 2.10
import QtQuick.Controls 2.3
import QtQuick.Layouts 1.3
import Qt.labs.calendar 1.0
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
CalendarModel {
id: myModel
from: new Date(2018, 0, 1)
to: new Date(2018, 11, 31)
}
ColumnLayout {
anchors.fill: parent
Label {
id: myLabel
text: "myLabel1"
}
Label {
text: myModel.monthAt(myView.currentIndex)
}
ListView {
id: myView
Layout.fillWidth: true
Layout.fillHeight: true
snapMode: ListView.SnapOneItem
orientation: ListView.Horizontal
highlightRangeMode: ListView.StrictlyEnforceRange
boundsBehavior: Flickable.StopAtBounds
model: myModel
// model: CalendarModel {
// id: myModel
// from: new Date(2018, 0, 1)
// to: new Date(2018, 11, 31)
// }
delegate: Rectangle {
color: "green"
width: myView.width
height: 200
Text {
anchors.centerIn: parent
text: model.month
}
}
onCurrentIndexChanged: {
console.log(currentIndex)
myLabel.text = String(currentIndex)
}
ScrollIndicator.horizontal: ScrollIndicator {}
}
}
}

How to set an item property of one qml from main.qml

I waste my time to find how set the visible property to false, the delegate being in an another qml file.
For instance here is a simple example based on Places Map.
Marker.qml
import QtQuick 2.0
import QtLocation 5.6
MapQuickItem {
id: idPointsMarker
sourceItem: Loader{sourceComponent: idRect}
visible: true //if set manually to false, everything works correctly
Component{
id: idRect
Rectangle{
width: 20
height: 20
color: "blue"
}
}
}
and the main.qml
import QtQuick 2.0
import QtQuick.Window 2.0
import QtLocation 5.6
import QtPositioning 5.6
Window {
width: 512
height: 512
visible: true
PositionSource {
...
}
property variant locationOslo: QtPositioning.coordinate( 59.93, 10.76)
PlaceSearchModel {
...
}
Map {
id: map
anchors.fill: parent
plugin: Plugin {name: "osm"}
center: locationOslo
zoomLevel: 13
MouseArea {
id : mouseMap
anchors.fill: parent
onDoubleClicked: {
console.log("DoubleClicked")
Marker.idPointsMarker.visible = false // pb is here
}
}
MapItemView {
model: searchModel
delegate: Marker{
coordinate: place.location.coordinate
}
}
}
}
I wish to toggle the visibility to false on doubleclick. I am not able to access the property anyhow the way i write it. What is the correct syntax?
Sorry for a so simple question. Thanks for help.
You do not have to set the property in main.qml, you must do it in Marker.qml, since the elements of Marker.qml can access all the elements of main.qml. One solution is to establish a property of type bool that manages the visibility and that changes in the double click:
main.qml
Map {
[...]
property bool isVisibleItems: true
MouseArea {
id : mouseMap
anchors.fill: parent
onDoubleClicked: map.isVisibleItems = !map.isVisibleItems
}
[...]
Marker.qml
import QtQuick 2.0
import QtLocation 5.6
MapQuickItem {
id: idPointsMarker
sourceItem: Loader{sourceComponent: idRect}
visible: map.isVisibleItems
Component{
id: idRect
Rectangle{
width: 20
height: 20
color: "blue"
}
}
}
In the following link there is an example

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.

How to add File name at recently opened file File menu

I want to write a QML app that adds the latest opened files from FileDialog to the main menu. I'm currently following this documentation example but the problem is that I can't understand how to pass the file name of an opened file.
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Dialogs 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
menuBar : MenuBar
{
Menu
{
id: recentFilesMenu
Instantiator
{
model: recentFilesMenu
MenuItem
{
text: model.fileName // I neeed to pass name of opned file here
}
onObjectAdded: recentFilesMenu.insertItem(index, object)
}
title: "File"
MenuItem
{
text: "Open"
onTriggered: fileDialog.visible = true
}
MenuItem
{
text: "Exit"
}
}
}
FileDialog
{
id: fileDialog
title: "Oooopen"
onAccepted:
{
// Here is problem
recentFilesMenu.objectName = fileDialog.fileUrls
}
}
}
According to the documentation, Instantiator accepts the most common types of models - both C++ and QML ones. In the documentation example such an information is missing, probably to not force the usage of a specific one. An actual implementation can relay on ListModel. In this case the model would expose a fileName role used as the actual menu item.
Following this approach the result would be something like the following code. Mind that the urls are prepended with information which can be easily removed (see for instance this answer).
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Dialogs 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
menuBar : MenuBar {
Menu {
id: recentFilesMenu
title: "File"
MenuItem {
text: "Open"
onTriggered: fileDialog.visible = true
}
MenuSeparator { }
Instantiator {
model: ListModel { id: files }
MenuItem { text: fileName }
onObjectAdded: recentFilesMenu.insertItem(index, object)
onObjectRemoved: recentFilesMenu.removeItem(object)
}
MenuSeparator { visible: files.count > 0 }
MenuItem { text: "Exit" }
}
}
FileDialog {
id: fileDialog
title: "Open"
onAccepted: {
for(var i = 0; i < fileDialog.fileUrls.length; ++i)
files.append({fileName: fileDialog.fileUrls[i]})
}
}
}
There is a widgets version of this kind of feature:
http://doc.qt.io/qt-5/qtwidgets-mainwindows-recentfiles-example.html
But the descriptive help is non-existent. Looking through the code here:
http://doc.qt.io/qt-5/qtwidgets-mainwindows-recentfiles-mainwindow-cpp.html
You will see that it stores a QStringList of a list of recent files in QSettings, and loads everything into an array of QActions.
Follow through the mainWindow.cpp for all the references to
enum { MaxRecentFiles = 5 };
QAction *recentFileActs[MaxRecentFiles];
And you should have some good ideas about how to do something similar in QML.
Hope that helps.
You probably have a finite number of recent files that you want to display. That being said, you can implement x number of MenuItems and set the text to QStringList[i] implemented as a Q_PROPERTY in a C++ class. Then, you can manipulate the QStringList elements(size, order) on your C++ class.

Resources