Keyboard events for Keys.onPressed not handled over some conditions - qt

I'm trying to get the button event from a USB camera on an application running under linux (custom built using Yocto Project) on an embedded system. Currently I'm using Qt 5.6.3. My problem is that the code I show right below works like a charm while I run the code through SSH from my pc (both via Qt Creator and a simple shell), but if I run the same program directly on the system without using SSH nothing happens when i click the button on the camera (nor any other key from a keyboard really).
Following some examples online I used Keys.onPressed and then filter the event to get the desired behaviour. To get it globally I put the event handler inside an Item directly in my ApplicationWindow.
ApplicationWindow {
Item {
focus: true
Keys.onPressed:{
console.log(event.key)
playSound.play() //I play a sound to be sure a button is clicked
if(camera.recording && event.key === 16777466) {
//do stuff for the right key here
}
}
}
//Other elements here
}
I think it has something to do with the X server running on my system. But everything is default and I really don't know what to look for in my system to get a hint of what's not working. Any advice il really appreciated.

Maybe a problem related with Focus. What about forcing the focus after onCompleted event?
ApplicationWindow {
Item {
id: myItem
focus: true
Keys.onPressed:{
console.log(event.key)
playSound.play() //I play a sound to be sure a button is clicked
if(camera.recording && event.key === 16777466) {
//do stuff for the right key here
}
}
Component.onCompleted: {
myItem.forceActiveFocus()
}
}
Component.onCompleted: {
myItem.forceActiveFocus()
}
//Other elements here
}

can you prove to set width and height of item?

After some hours of searching it turned out it was really a problem with the X server's "active window", the solution was very simple though, I just had to add requestActivate(); on my main view just like this:
ApplicationWindow {
Item {
focus: true
Keys.onPressed:{
console.log(event.key)
playSound.play() //I play a sound to be sure a button is clicked
if(camera.recording && event.key === 16777466) {
//do stuff for the right key here
}
}
}
StackView{
id: rootView
width: 1280
height: 800
Component.onCompleted: {
requestActivate(); //THIS SOLVED THE PROBLEM
push(mainarea);
}
//Other elements here
}

Related

What are these glitches in my listview when scrolling?

I'm writing a file conversion software in QT for Python where you will be able to drag files into the software, click a convert button, and drag out the output files. When a user drags files into the software, all the names of the files are added into a ListView.
When a user drags files into the ListView, it calls the backend.addToPaths(url) function with each of the file paths that were dragged into it. This function then appends all of the file paths into an internal list of file paths, then updates the listview, calling the updateList (paths) function in the main.qml file with all of the file names, which clears the listview and then appends back all of the file names, the old ones, and the new ones dragged in.
All of the file names are added to the list view correctly, but then when I scroll around inside of the list view, it produces these very strange rendering bugs, as shown in this video, or in these images:
Image 1:
Image 2:
Image 3:
At first I thought it could be due to clipping, so I removed that, and nothing changed. I then tried increasing the listview's display margin, and then its cacheBuffer, but it still didn't help. I also tried setting pixelAligned to true, but that still didn't work. I'm guessing it's probably because QT isn't very good at handling listmodels being updated or changed, but I don't really know.
Here's a simplified version of my main.qml file if needed:
ListView {
id: inputFileView
// #disable-check M16
objectName: "inputFileView"
clip: true
boundsBehavior: Flickable.StopAtBounds
flickableDirection: Flickable.VerticalFlick
displayMarginBeginning: 100
displayMarginEnd: 100
function updateList(paths) {
console.log("updating list");
inputFileModel.clear();
paths.forEach( function (item) {
inputFileModel.append({
'name': item
});
});
}
model: ListModel {
id: inputFileModel
}
delegate: Item {
Row {
id: row1
Text {
text: name
}
}
}
DropArea {
anchors.fill: parent
onDropped: {
drop.urls.forEach( function (url) {
backend.addToPaths(url)
});
}
}
}
I guess it was a bug with PySide2? I noticed someone replaced the Pyside tag with the PySide2 tag, and I didn't even show the python code that would've clarified that I was using that version, so I wondered if it meant that the issue was only in PySide2, so I switched from that to PySide6, and it worked. I have no idea what was causing it, but I guess it's fine now.

Get Portable KeySequence QString from shortcut in QML

I need to set shortcuts and then display them as text in a window. How do I set it using Windows-Style but retrieve the adapted key sequence depending on the OS?
For example, if I do something like this, I want to get Ctrl+O on Windows, and Cmd+O on MacOSX.
Window {
visible: true
MainForm {
anchors.fill: parent
mouseArea.onClicked:
{
console.log(shortcut.sequence)
console.log(shortcut.portableText)
}
}
Shortcut
{
id: shortcut
sequence:"Ctrl+O"
}
}

Crash in QQuickItem destructor / changeListeners when closing application (Qt 5.6)

We have a fairly big QtQuick application, with a lot of modal dialogs. All of these modals share a consistent look and behaviour, and have leftButtons, rightButtons, a content and additional warning widgets. We use the following base class (PFDialog.qml):
Window {
property alias content: contentLayout.children
ColumnLayout {
id: contentLayout
}
}
and declare dialogs in the following way (main.qml):
Window {
visible: true
property var window: PFDialog {
content: Text { text: "Foobar" }
}
}
The problem is that when the application is closed, a segfault happens in the QQuickItem destructor. This segfault is hard to reproduce, but here is a surefire way of making it happen: with visual studio in debug mode, freed memory is filled with 0xDDDDDDD with triggers the segfault every time.
Full example application can be found here: https://github.com/wesen/testWindowCrash
The crash happens in QQuickItem::~QQuickItem:
for (int ii = 0; ii < d->changeListeners.count(); ++ii) {
QQuickAnchorsPrivate *anchor = d->changeListeners.at(ii).listener->anchorPrivate();
if (anchor)
anchor->clearItem(this);
}
The reason for this is that the content of our dialog (the Text item in the example above) is a QObject child of the main Window, but a visual child of the dialog window. When closing the application, the dialog window is destroyed first, and at the time the Text item is deleted, the dialog window (still registered as a changeListener) is stale.
Now my question is:
is this a QtQuick bug? Should the dialog deregister itself as a changeListener for its children when it is destroyed (I think it should)
is our property alias content: layout.children pattern correct, or is there a better way to do this? This also happens when declaring a default property alias.
For the sake of completeness, here is how we hotfix it in our application. When content changes, we reparent all the items to the layout item. A of elegance, as you will all agree.
function reparentTo(objects, newParent) {
for (var i = 0; i < objects.length; i++) {
qmlHelpers.qml_SetQObjectParent(objects[i], newParent)
}
}
onContentChanged: reparentTo(content, contentLayout)
I have had this problem lots of times, I don't think it is a bug, more like a design limitation. The more implicit behavior you get, the less control you have, leading to inappropriate orders of object destruction and access to dangling references.
There are numerous situations where this can happen "on its own" as you exceed the bounds of a trivial "by the book" qml application, but in your case it is you who's doing it.
If you want proper ownership, don't use this:
property var window: PFDialog {
content: Text { text: "Foobar" }
}
Instead use this:
property Window window: dlg // if you need to access it externally
PFDialog {
id: dlg
content: Text { text: "Foobar" }
}
Here is a good reason why:
property var item : Item {
Item {
Component.onCompleted: console.log(parent) // qml: QQuickItem(0x4ed720) - OK
}
}
// vs
property var item : Item {
property var i: Item {
Component.onCompleted: console.log(parent) // qml: null - BAD
}
}
A child is not the same as a property. Properties are still collected but they are not parented.
As for achieving the "dynamic content" thingie, I've had good results with ObjectModel:
Window {
property ObjectModel layout
ListView {
width: contentItem.childrenRect.width // expand to content size
height: contentItem.childrenRect.height
model: layout
interactive: false // don't flick
orientation: ListView.Vertical
}
}
Then:
PFDialog {
layout: ObjectModel {
Text { text: "Foobar" }
// other stuff
}
}
Lastly, for the sake of doing explicit cleanups before closing the application, on your main QML file you can implement a handler:
onClosing: {
if (!canExit) doCleanup()
close.accepted = true
}
This ensures the window will not be destroyed without doing the cleanup first.
Finally:
is our property alias content: layout.children pattern correct, or is
there a better way to do this? This also happens when declaring a
default property alias.
It wasn't last time I looked into it, but it was at least couple of years back. It would certainly be nice to have objects declared as children actually becoming children of some other object, but at the time this was not possible, and still may not be. Thus the need for the slightly more verbose solution involving the object model and the list view. If you investigate the matter and find something different, leave a comment to let me know.
I believe that you cannot declare a Window Object in a var. In my tests the SubWindow never open and sometimes broken on startup.
A Window can be declared inside an Item or inside another Window; in that case the inner Window will automatically become "transient for" the outer Window
See: http://doc.qt.io/qt-5/qml-qtquick-window-window.html
Modify your code to this:
Window {
visible: true
PFDialog {
content: Text { text: "Foobar" }
}
}

Qt 5 QML app with lots of Windows or complex UIs

In QtQuick 2 using the QtQuick Controls you can create complex desktop apps. However it seems to me that the entire UI must be declared and create all at once at the start of the app. Any parts that you don't want to use yet (for example the File->Open dialog) must still be created but they are hidden, like this:
ApplicationWindow {
FileDialog {
id: fileOpenDialog
visible: false
// ...
}
FileDialog {
id: fileSaveDialog
visible: false
// ...
}
// And so on for every window in your app and every piece of UI.
Now, this may be fine for simple apps, but for complex ones or apps with many dialogs surely this is a crazy thing to do? In the traditional QtWidgets model you would dynamically create your dialog when needed.
I know there are some workarounds for this, e.g. you can use a Loader or even create QML objects dynamically directly in javascript, but they are very ugly and you lose all the benefits of the nice QML syntax. Also you can't really "unload" the components. Well Loader claims you can but I tried it and my app crashed.
Is there an elegant solution to this problem? Or do I simply have to bite the bullet and create all the potential UI for my app at once and then hide most of it?
Note: this page has information about using Loaders to get around this, but as you can see it is not a very nice solution.
Edit 1 - Why is Loader suboptimal?
Ok, to show you why Loader is not really that pleasant, consider this example which starts some complex task and waits for a result. Suppose that - unlike all the trivial examples people usually give - the task has many inputs and several outputs.
This is the Loader solution:
Window {
Loader {
id: task
source: "ComplexTask.qml"
active: false
}
TextField {
id: input1
}
TextField {
id: output1
}
Button {
text: "Begin complex task"
onClicked: {
// Show the task.
if (task.active === false)
{
task.active = true;
// Connect completed signal if it hasn't been already.
task.item.taskCompleted.connect(onTaskCompleted)
}
view.item.input1 = input1.text;
// And several more lines of that...
}
}
}
function onTaskCompleted()
{
output1.text = view.item.output1
// And several more lines...
// This actually causes a crash in my code:
// view.active = false;
}
}
If I was doing it without Loader, I could have something like this:
Window {
ComplexTask {
id: task
taskInput1: input1.text
componentLoaded: false
onCompleted: componentLoaded = false
}
TextField {
id: input1
}
TextField {
id: output1
text: task.taskOutput1
}
Button {
text: "Begin complex task"
onClicked: task.componentLoaded = true
}
}
That is obviously way simpler. What I clearly want is some way for the ComplexTask to be loaded and have all its declarative relationships activated when componentLoaded is set to true, and then have the relationships disconnected and unload the component when componentLoaded is set to false. I'm pretty sure there is no way to make something like this in Qt currently.
Creating QML components from JS dynamically is just as ugly as creating widgets from C++ dynamically (if not less so, as it is actually more flexible). There is nothing ugly about it, you can implement your QML components in separate files, use every assistance Creator provides in their creation, and instantiate those components wherever you need them as much as you need them. It is far uglier to have everything hidden from the get go, it is also a lot heavier and it could not possibly anticipate everything that might happen as well dynamic component instantiation can.
Here is a minimalistic self-contained example, it doesn't even use a loader, since the dialog is locally available QML file.
Dialog.qml
Rectangle {
id: dialog
anchors.fill: parent
color: "lightblue"
property var target : null
Column {
TextField {
id: name
text: "new name"
}
Button {
text: "OK"
onClicked: {
if (target) target.text = name.text
dialog.destroy()
}
}
Button {
text: "Cancel"
onClicked: dialog.destroy()
}
}
}
main.qml
ApplicationWindow {
visible: true
width: 200
height: 200
Button {
id: button
text: "rename me"
width: 200
onClicked: {
var component = Qt.createComponent("Dialog.qml")
var obj = component.createObject(overlay)
obj.target = button
}
}
Item {
id: overlay
anchors.fill: parent
}
}
Also, the above example is very barebone and just for the sake of illustration, consider using a stack view, either your own implementation or the available since 5.1 stock StackView.
Here's a slight alternative to ddriver's answer that doesn't call Qt.createComponent() every time you create an instance of that component (which will be quite slow):
// Message dialog box component.
Component {
id: messageBoxFactory
MessageDialog {
}
}
// Create and show a new message box.
function showMessage(text, title, modal)
{
if (typeof modal === 'undefined')
modal = true;
// mainWindow is the parent. We can also specify initial property values.
var messageDialog = messageBoxFactory.createObject(mainWindow, {
text: text,
title: title,
visible: true,
modality: modal ? Qt.ApplicationModal : Qt.NonModal
} );
messageDialog.accepted.connect(messageDialog.destroy);
messageDialog.rejected.connect(messageDialog.destroy);
}
I think loading and unloading elements is not actual any more because every user have more than 2GB RAM.
And do you think your app can take more than even 512 MB ram? I doubt it.
You should load qml elements and don't unload them, no crashes will happens, just store all pointers and manipulate qml frames.
If you just keep all your QML elements in RAM and store their states, it will works faster and looks better.
Example is my project that developed in that way: https://youtube.com/watch?v=UTMOd2s9Vkk
I have made base frame that inherited by all windows. This frame does have methods hide/show and resetState. Base window does contains all child frames, so via signal/slots other frames show/hide next required frame.

Handle key events Ctrl+Tab and Ctrl+Shift+Tab

I want to handle the two key events Ctrl+Tab and Ctrl+Shift+Tab in order to switch between tabs in my application ("forward" and "backward" respectively). However, this doesn't seem to work as expected.
This is my current code (minimal example):
import QtQuick 1.1
Item {
width: 100
height: 100
focus: true
Keys.onPressed: {
if(event.modifiers & Qt.ControlModifier) {
if(event.key === Qt.Key_Tab) {
if(event.modifiers & Qt.ShiftModifier)
console.log('backward')
else
console.log('forward')
}
}
}
}
I ran this piece of code with qmlviewer (Qt version 4.8.2)
Output when pressing Ctrl+Tab:
forward
forward
Output when pressing Ctrl+Shift+Tab:
none
So I see two errors: The former key sequence is handled twice while the other one not at all.
EDIT: The reason that the other one doesn't get handled at all is solved, see comments.
Why does this happen and how can I solve this?
Note: I already use Qt Components for Desktop in my application, so it's OK if you know a solution requiring this module.
You have to accept the event, otherwise the event is propagated to the parents until it is accepted. The following code worked for me.
Item {
width: 100
height: 100
focus: true
Keys.onPressed: {
if(event.modifiers && Qt.ControlModifier) {
if(event.key === Qt.Key_Tab) {
console.log('forward')
event.accepted = true;
}
else if(event.key === Qt.Key_Backtab) {
console.log('backward')
event.accepted = true;
}
}
}
}
Edit: This behavior lets parents handle events that the child could not, for things like hotkeys.
Hope this helps!

Resources