QML Video element randomly disappears on Label text change - qt

I'm working on an app which is supposed to display a camera stream from a webcam. It's a single-page app which only shows a Video QML element showing the stream (which currently is a simple .avi file) and a Label element indicating the current connection state from an MQTT connection.
Here's the code:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.1
import QtMultimedia 5.12
import MqttClient 1.0
Window {
width: 360
height: 640
visible: true
title: qsTr("Doorbell")
MqttClient {
id: client
// TODO
property string _host: "localhost"
property string _port: "1883"
property string _topic: "my/topic"
hostname: _host
port: _port
Component.onCompleted: {
connectToHost()
}
onConnected: {
subscribe(_topic)
}
onMessageReceived: {
video.play()
}
Component.onDestruction: {
disconnectFromHost()
}
}
GridLayout {
anchors.fill: parent
anchors.margins: 10
columns: 2
Video {
id: video
objectName: "vplayer"
width: parent.width
height: 300
Layout.columnSpan: 2
autoPlay: false
source: "file:///path/to/my/test.avi"
onErrorChanged: {
console.log("error: " + video.errorString)
}
MouseArea {
anchors.fill: parent
onClicked: {
video.muted = !video.muted
}
}
focus: true
Image {
id: muteIndicator
source: "mute_white.png"
width: 64
height: width
visible: video.muted
anchors.centerIn: parent
}
}
Label {
function stateToString(value) {
if (value === 0)
return "Disconnected"
else if (value === 1)
return "Connecting"
else if (value === 2)
return "Connected"
else
return "Unknown"
}
Layout.columnSpan: 2
Layout.fillWidth: true
text: stateToString(client.state) + "(" + client.state + ")"
}
}
}
Here's a screenshot:
Here's the clue:
I tried removing the Label and replacing it with a simple rectangle indicator (red or green) to show if the connection is currently active.
However, when replacing the text content of the Label element, the Video element completely disappears.
What I've tried:
removing the stateToString(client.state) + "(" + client.state + ")" part and replacing it with text: "Connected(2)"
replacing stateToString(... with an empty string (text: "")
replacing the content of stateToString(...) with return "Connected(2)"
and a lot of different more seemingly completely useless things
Example code:
// ...
Label {
function stateToString(value) {
if (value === 0)
return "Disconnected"
else if (value === 1)
return "Connecting"
else if (value === 2)
return "Connected"
else
return "Unknown"
}
Layout.columnSpan: 2
Layout.fillWidth: true
text: "Connected(2)"
// enabled: client.state === MqttClient.Connected
}
// ...
Unless I set text to the exact value stateToString(client.state) + "(" + client.state + ")" or at least stateToString(client.state), the Video element will always disappear in the QML view:
I have no idea of what might be the reason for this.
Any help is greatly appreciated, thanks.

Try adding:
Layout.fillWidth: true
after:
objectName: "vplayer"
I'm 99% sure the root of the problem is in the way you have used the layouts. In another word, you have not placed your QML elements in a robust way. since QML has so much flexibility in positioning elements in UI, it matters in QML to put your elements in a well-defined, robust way.

Related

How to reset style for rich text in QML TextArea

If I insert rich text in QML TextArea, it will preserve that style (text color, underline etc.) for further inputs. Is there a way to prevent that from happening?
Example:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
TextArea {
id: textArea
textFormat: Qt.RichText
focus: true
selectByMouse: true
selectByKeyboard: true
Keys.onPressed: {
if (event.text === "#") {
textArea.text += "<a href='mentioned://user'>#User</a>";
event.accepted = true
}
}
}
}
When I enter "#" character it will insert the <a> link instead, but when I continue typing other characters it will append them to the link, as if they are a part of it. How can I continue typing a new paragraph, without appending to the link ( tag)?
Adding a whitespace after the tag solves the problem :
Window {
width: 640;
height: 480;
visible: true;
title: qsTr("Code from #Meliodas on StackOverflow");
TextArea {
id: textArea;
textFormat: Qt.RichText;
focus: true;
selectByMouse: true;
selectByKeyboard: true;
Keys.onPressed: (event) => {
if (event.text === "#") {
// HERE
insert(cursorPosition, "<a href='mentioned://user'>#User</a> ");
event.accepted = true;
}
}
}
}
Note that I took the freedom of modifying other pieces of your code :
insert() instead of text += to avoid automatic newlines
explicitly defining event to silence a warning telling me implicit event parameters are deprecated

ContainsMouse gives incorrect value on parent change

In QML, the MouseArea's containsMouse property is supposed to return true when the mouse is currently inside the mouse area. Unfortunately, this is not always the case. In the following code, the red square turns blue when the MouseArea within it contains the mouse (ContainsMouse is true). However, if you hit the control key while the square is blue, when the square is reparented to the Window's contentItem, the containsMouse property is not updated (as indicated by the text in the middle of the square). The square will still be blue even though it doesn't contain the mouse anymore. Is there anyway to tell the MouseArea to refresh it's containsMouse property?
Here is the code:
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
width: 800
height: 500
visible: true
Rectangle {
id: square
width: 200
height: 200
focus: true
color: my_mouse_area.containsMouse ? "blue" : "red"
MouseArea {
id: my_mouse_area
anchors.fill: parent
hoverEnabled: true
onClicked: {
my_mouse_area.x = 200
}
}
Text {
anchors.centerIn: parent
text: my_mouse_area.containsMouse + ""
font.pixelSize: 20
}
Keys.onPressed: {
if(event.key === Qt.Key_Control){
second_window.show()
square.parent = second_window.contentItem
}
}
}
Window {
id: second_window
width: 400
height: 400
visible: false
}
}
I don't like my first solution, so I have made another, more sophisticated one, but this is not a pure QML solution. The trick is that on parent change you should call a C++ method where you send a mouse move event back to the mouse area, so it will re-evaluate the hovered aka containsMouse boolean. It is a nicer solution, but still a bit of a workaround.
Make sure you have a simple QObject derived class like MyObject with the following Q_INVOKABLE method:
class MyObject : public QObject
{
Q_OBJECT
//
// constuctor and whatnot
//
Q_INVOKABLE void sendMouseMoveEventTo(QObject* item)
{
QEvent* e = new QEvent(QEvent::MouseMove);
QCoreApplication::sendEvent(item, e);
}
};
Make an instance of it in main.cpp, and set as context property, so you can reach it from QML:
MyObject myObject;
engine.rootContext()->setContextProperty("myObject", &myObject);
And finally in the QML Rectangle add this:
onParentChanged: {
myObject.sendMouseMoveEventTo(my_mouse_area)
}
The solution I came up with uses Timer, but with zero interval, thus zero flickering. You can try setting the interval to higher value, to see what is going on. The trick is to set the rectangle visibility dependent of the timer running using "visible: !tmr.running", and start the timer immediately after the parent change of the rectangle.
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
width: 800
height: 500
visible: true
Rectangle {
id: square
width: 200
height: 200
focus: true
color: my_mouse_area.containsMouse ? "blue" : "red"
visible: !tmr.running
Timer {
id: tmr
interval: 0
}
MouseArea {
id: my_mouse_area
anchors.fill: parent
hoverEnabled: true
onClicked: {
my_mouse_area.x = 200
}
}
Text {
anchors.centerIn: parent
text: my_mouse_area.containsMouse + ""
font.pixelSize: 20
}
Keys.onPressed: {
if(event.key === Qt.Key_Control){
second_window.show()
square.parent = second_window.contentItem
tmr.start()
}
}
}
Window {
id: second_window
width: 400
height: 400
visible: false
}
}

QML prevent ListView delegate to update all the time

I'm relatively new to QML/QtQuick and still learning. I have a little performane issue with a very small private project. I just tryed to implement a filter function to my ListView, because >15.000 objects are a lot to search manually. I just want to update the ListView when I finished the editing of my search field or pressing "return". But instead it's refreshing every time I insert or delete a character from this textfield which needs sometimes a few seconds.
Anyone have an idea how to prevent the list to be refreshed permanently or reducing theese performance issues?
Thanks a lot
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.XmlListModel 2.12
import Anime_initialiser 1.0
import "."
Page {
TextField{
id: searchField
width: parent.width
z: 1
/*onEditingFinished: {
XL.animeListModel.reload()
}*/
}
ListView {
z: 0
ScrollBar.vertical: ScrollBar { active: true }
id: listView
width: parent.width
height: parent.height
model: XL.animeListModel
y: searchField.height
Anime_initialiser {
id: initialiser
onShowAnimeDetails: {
xmlDataString = xmlString
swipeView.currentIndex = swipeView.currentIndex+1
}
}
delegate: ItemDelegate {
visible: {
if (searchField.length > 0)
return (main_title.toLowerCase().match(searchField.text.toLowerCase()) || de_title.toLowerCase().match(searchField.text.toLowerCase())) ? true : false
else
return true
}
height: visible ? Button.height : 0
width: parent ? parent.width : 0
Button {
anchors.fill: parent
onClicked: {
anime_id = aid
initialiser.buttonClicked(anime_id)
}
Text {
width: parent.width
height: parent.height
font.pointSize: 100
minimumPointSize: 12
fontSizeMode: Text.Fit
text: aid + ": " + main_title + (de_title ? "\nDE: " + de_title : "")
}
}
}
}
}
Rather than toggling the visible flag of all of your delegates, you should use a QSortFilterProxyModel. The idea is that the proxy model would use your XL.animeListModel as a source model, and then you can give the proxy a regular expression telling it which ones to filter out. Depending on how you want it to filter, you could just call setFilterRole() to tell it which property to compare against your regex, or you could do a custom filter by overriding the filterAcceptsRow() function.
EDIT:
If you don't want to use a proxy, you can still prevent the constant updates by not binding on the visible property directly to the search field. You were on the right track with your onEditingFinished code. You could create a separate text string that just holds the completed search text.
property string searchText: ""
Then update that string when you are done typing your search text.
onEditingFinished: {
searchText = searchField.text.toLowerCase();
}
And finally, bind your visible property to this new string.
visible: {
if (searchText.length > 0)
return (main_title.toLowerCase().match(searchText) || de_title.toLowerCase().match(searchText)) ? true : false
else
return true
}

Qt5/QML - Pagination in Text/TextArea

Let's say I have a QML Text or TextArea that contains a very long HTML page. I want to make it easier to read by splitting it into pages.
More specifically, every time I press the down key, I want it to scroll down until none of the current text on the screen is still there.
I already know how to make the entire TextArea scrollable; that's not what I'm looking for. What I'm looking for is more like the kind of behavior you'd expect in an ebook reader.
Is there any way to do something like that, preferably in pure QML (though C++ is also fine).
You can measure the TextArea height after loading, divide it to the container height and so get the count of pages. Then you just move the TextArea relative to its container according to the current page.
The simple illustration of my idea:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
Window {
id: main
visible: true
width: 640
height: 800
property int currentPage: 1
property int pageCount: 1
ColumnLayout
{
anchors.fill: parent
anchors.margins: 5
RowLayout {
Layout.preferredHeight: 40
Layout.alignment: Qt.AlignHCenter
Button {
text: "<"
onClicked: {
if(main.currentPage > 1)
main.currentPage --;
}
}
Text {
text: main.currentPage + " / " + main.pageCount
}
Button {
text: ">"
onClicked: {
if(main.currentPage < main.pageCount)
main.currentPage ++;
}
}
}
Rectangle {
id: container
clip: true
Layout.fillHeight: true
Layout.fillWidth: true
TextArea {
id: msg
text: "Loading ..."
width: container.width
height: container.height
y: -(main.currentPage - 1) * container.height
textFormat: TextEdit.RichText
wrapMode: TextEdit.Wrap
Component.onCompleted: {
msg.makeRequest();
}
onContentHeightChanged: {
msg.height = msg.contentHeight;
if(msg.contentHeight >= container.height && container.height > 0)
{
main.pageCount = msg.contentHeight / container.height;
loader.running = false;
}
}
function makeRequest()
{
var doc = new XMLHttpRequest();
msg.text = "";
doc.onreadystatechange = function() {
if (doc.readyState === XMLHttpRequest.DONE) {
msg.text = doc.responseText;
}
}
doc.open("GET", "http://www.gutenberg.org/files/730/730-h/730-h.htm");
doc.send();
}
}
}
}
BusyIndicator {
id: loader
running: true
anchors.centerIn: parent
}
}
Of course you have to process margins, the last line on a page, recalculate the values on resizing etc.

Clear QML anchor

I have a MouseArea that I want to start off centered and then have an absolute position once the up/down/left/right keys are pressed. My problem is that I don't know how to clear the anchor on the MouseArea so that I can specify an absolute position:
import QtQuick 2.0
import QtQuick.Window 2.0
Window {
id: screen
width: 360
height: 360
visible: true
Rectangle {
anchors.fill: parent
states: [
State {
name: "moved"
AnchorChanges {
target: mouseArea
anchors.bottom: undefined
anchors.left: undefined
anchors.right: undefined
anchors.top: undefined
}
}
]
MouseArea {
id: mouseArea
anchors.centerIn: parent
width: 250
height: 250
focus: true
onClicked: console.log("clicked!")
onPositionChanged: console.log("position changed!")
function moveMouseArea(x, y) {
mouseArea.x += x;
mouseArea.y += y;
mouseArea.state = "moved";
mouseAreaPosText.text = 'Mouse area was moved... new pos: '
+ mouseArea.x + ', ' + mouseArea.y;
}
Keys.onPressed: {
if (event.key === Qt.Key_Up)
moveMouseArea(0, -1);
if (event.key === Qt.Key_Down)
moveMouseArea(0, 1);
if (event.key === Qt.Key_Left)
moveMouseArea(-1, 0);
if (event.key === Qt.Key_Right)
moveMouseArea(1, 0);
}
Rectangle {
anchors.fill: parent
border.width: 2
border.color: "black"
color: "transparent"
}
Text {
id: mouseAreaPosText
anchors.centerIn: parent
}
}
}
}
At first I just tried setting mouseArea.anchors to undefined but got an error about anchors being a read-only property. I then discovered AnchorChanges, but I can't find a way to remove/clear the anchor; setting anchors.bottom etc. to undefined doesn't work.
According to docs, setting an anchor attribute to undefined should work. I don't quite get why AnchorChanges did not allow to set anchors.centerIn, but you can workaround it in your moveMouseArea function:
function moveMouseArea(x, y) {
mouseArea.anchors.centerIn = undefined; // <-- reset anchor before state change
mouseArea.pos.x += x;
mouseArea.pos.y += y;
mouseArea.state = "moved";
mouseAreaPosText.text = 'Mouse area was moved... new pos: '
+ mouseArea.pos.x + ', ' + mouseArea.pos.y;
}
Thanks for your help guys. I have found that setting undefined within a state works (if by works you mean only that it doesn't give errors), however once the element moves to yet another state, the anchors magically (and very frustratingly) return. This happens EVEN if you set all anchors undefined in the final state. As mentioned above however, setting undefined in the function before changing state works great. In my case, I set it in my mouseArea in onPressed.
onPressed: {
plotWindow04Frame.anchors.bottom = undefined
plotWindow04Frame.anchors.left = undefined
plotWindow04Frame.state = "inDrag"
}
I found it was not necessary to mention the anchor in the onReleased, just the next state.
onReleased: {
plotWindow04Frame.state = "dropped"
}
Also, I should mention, that the final "dropped" state does not mention anchors either, just opacity.
states: [
State {
name: "inDrag"
PropertyChanges {
target: plotWindow04Frame
opacity: .5
}
},
State {
name: "dropped"
PropertyChanges {
target: plotWindow04Frame
opacity: 1
}
}
]
transitions: Transition {
NumberAnimation { properties: "opacity"; duration:200 }
}
}
(The idea here was that these plot windows would become translucent (opacity: 0.5) while dragging, but return to opaque (opacity: 1) when the user drops them)
What is nice is that the plotwindow "rectangles" are initially anchored to the bottom of the GUI, but once the user picks them up, they can put them where ever they like.

Resources