Unable to loop video using QML MediaPlayer - qt

I am trying to create a simple video player that just plays a specified video on loop. While the video plays as expected, it does not loop.
The following is the code I am using:
import QtQuick 2.0
import QtMultimedia 5.0
Rectangle
{
width : 320
height : 240
signal buttonPressed(string msg)
property string currentVideo
function playVideo(videoName)
{
currentVideo = videoName
videoPlayer.source = videoName
videoPlayer.seek(1)
videoPlayer.play()
}
function loopVideo()
{
if(videoPlayer.duration === 0)
{
playVideo(currentVideo)
}
}
function stopVideoPlayback()
{
videoPlayer.stop()
}
MediaPlayer {
id: videoPlayer
source: ""
autoPlay: false
autoLoad: false
loops: 100
}
VideoOutput {
id: videoOutput
source: videoPlayer
anchors.fill: parent
visible: true
}
}
I call playVideo from C++. It starts playing as expected. However, once it completes, the frame freezes on the last one. I tried looping it by calling the loopVideo function in a QTimer. That does not work either.
What might I be doing wrong?

Your code is ok. (slight tip: you might want to use MediaPlayer.Infinite instead 100 for looping)
I believe that your situation is same like mine.
I have played a little with MediaPlayer component and at my end I am unable to seek video because seekable is always false. And seekable is false because somehow QML uses my file as live stream, and that results duration property to be 0.
Also note that onPaused and onStopped are never triggered and position is just increasing after end of video (live stream never ends).
Now I think that this is related to looping, because basically looping seeks back to 0. Because there is no duration (MediaPlayer thinks it is live stream) it cannot seek (and loop).
One nasty workaround that I found is this (append to your code):
Rectangle {
id: root
//...
MediaPlayer {
//...
onPositionChanged: {
if (position > VIDEO_LENGTH) {
root.stopVideoPlayback()
root.playVideo(root.currentVideo)
}
}
}
}
Where VIDEO_LENGTH is length of your video file in milliseconds.
Click here for MediaPlayer element documentation
UPDATE:
It looks like that is bug in Qt for mingw version (closed bug report).
UPDATE 2: I have downloaded MSVC version of Qt and media player works as it is supposed.
So it is bug in Qt for mingw.
Either use this workaround (which I wouldn't recommend) or download MSVC version.
I have created new bug report here.

Using stopped signal try this code :
MediaPlayer {
id: mediaplayer
source: "groovy_video.mp4"
onStopped: play()
}

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.

How qml MediaPlayer VideoOutput run in separate thread?

Suppose there is a code like this (sorry for the contrived code)
Window {
id: window
visible: true
width: 700
height: 700
MediaPlayer {
id: mediaplayer
source: "test.avi"
autoPlay: true
}
VideoOutput {
anchors.fill: parent
source: mediaplayer
}
Repeater {
id: repeater
property int n: 1
model: 1
Label {
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max))
}
id: label
y: getRandomInt(window.width)
x: getRandomInt(window.height)
text: "label"
}
}
Timer {
interval: 10
running: true
repeat: true
onTriggered: {
repeater.n += 1
if (!(repeater.n % 100)) {
repeater.model = repeater.n
}
}
}
}
When the number of labels increases, the video starts to break. How to start a video in a separate thread so that manipulations with any widgets do not interrupt it (video).
You should not overload main thread (with it's event loop). Otherwise, whole the software will lag, not only VideoOutput.
Don't move to another thread well-optimized and efficient controls. Move to another thread huge things, hard & long computations.
So
avoid using timers with low interval or if you use them, don't attach to them hard things
if you should create many or hard controls in QML, then use Loader or QQmlIncubator, they allow to create QML controls in a separate threads. Also Loader allows dynamically load and unload needed/unneeded controls. So, QML engine will not render too many controls, most of which even are not visible.
Note about Loader/QQmlIncubator: they create control in a separate thread, not run it there.
avoid writing custom properties and functions inside QML controls, place them in some single QtObject: QtObject { id: internals; ...all your custom data... }
Use ListView instead of Repeater. It's more efficient because it instantiates only visible items (and several out of visible area) - probably the most important for your sample
More advice and samples you can find here:
Performance Considerations And Suggestions: https://doc.qt.io/qt-5/qtquick-performance.html
QML performance tips and tricks: https://katastrophos.net/harmattan-dev/html/guide/html/Developer_Library_Best_practices_for_application_development_QML_performance_tips_and_tricks.html
QtObject: https://doc.qt.io/qt-5/qml-qtqml-qtobject.html

How to inject data into QT item shown with loader

In my application I have a global system that handles navigation between "screens". In QML I can simply call something like:
appNavigation.show("MyScreen.qml", NavigationType.FADE)
this calls a C++ part of the code which handles the current stack of screens and uses signals to report back to QML to do the actual animation. At the end in QML some Loader will load the input qml ("MyScreen.qml" in this case) and show it as defined.
My issue here is how to inject data into newly loaded screen. Essentially I would like to do something like the following:
function showMyScreen() {
MyScreen screen = appNavigation.show("MyScreen.qml", NavigationType.FADE)
screen.someData = "some data here"
}
but is this possible? Could I somehow return the screen that is loaded by the loader?
I am guessing not so I would satisfy with sending the data with the navigation itself like:
function showMyScreen() {
MyScreen screen = appNavigation.show("MyScreen.qml", NavigationType.FADE, "some data here")
}
I could forward the data to the point where I set source to the loader but still what then? How or where would that specific screen that is going to be loaded get the data. To reduce is this is what I get:
function setNewItemWithData(newItem, data) {
loader.source = newItem
loader.concreteScreen.data = data // Not really doable
}
again I assume this is not doable and I need to forward the data down to loader and use onLoaded event. So what I would do is something like:
onLoaded: {
myLoadedScreen.data = data
}
I assume something like this is possible but how? What am I missing here, how do I get myLoadedScreen and how to access its properties?
What I am currently doing now is dumping the data in C++ part and then collecting it in the loaded QML. So like the following:
appNavigation.injectedData = "some data here"
and then in the newly loaded item:
property data = appNavigation.injectedData
It works but this seems like extremely poor coding. Any of the alternatives would be helpful.
Thank you for your patience.
Since the request for MCVE was made:
This is a general problem and I expect it to have multiple solutions. I would be looking forward to any of them. However the minimal example to produce this is creating a new project and adding a loader with another qml to which some property should be changed:
main:
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Loader {
anchors.fill: parent; anchors.margins: 20
source: "MyScreen.qml"
// TODO: make screen green (loadedScreen.color = "green")
}
}
MyScreen:
import QtQuick 2.0
Rectangle {
color: "red"
}
Current result is seeing a red rectangle and desired result is to see a green one. The point being that the main screen needs to tell what color the loaded screen needs to use.
You have to use the item property of the Loader to get the object loaded:
Loader {
id: loader
anchors.fill: parent; anchors.margins: 20
source: "MyScreen.qml"
onLoaded: loader.item.color = "green"
}
To do that, you might as well use Component (If you use it when reacting to an event)
Component {
id: myScreenComponent
MyScreen {
anchors.fill: parent
}
}
function showMyScreen() {
myScreenComponent.createObject(this, {"color: "green"});
}
Alternatively, given your first code, I would recommend you to use StackView.
The push method seems to be similar to your appNavigation.show one.
You can give it an url, some properties, and a transition type (that you can customize).

Qt/QML: Trying to create a log file view with TextEdit, result is really slow

I am working on an Android App. I need to display a console like type of log, which will be written to by the C++ back end. I have tried doing this combining a TextEdit and ScrollView, but the result is really slow. As soon as my log goes beyond ~50 lines, adding a few lines slows down (locks) the interface for a few seconds.
Trimming down the source code, this is the log view section:
property int logMaxLines: 50
ScrollView {
id: logScrollView
anchors.fill: parent
clip: true
ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
TextEdit {
id: logTextEdit
anchors.fill: parent
readOnly: true
color: "darkgreen"
property int linesTrimmed: 0
}
}
Connections{
target: gate
onNewMessageLineAdded :
{
logTextEdit.append(gate.newMessageLine)
if (logTextEdit.lineCount > logMaxLines) {
while (logTextEdit.lineCount >= logMaxLines) {
logTextEdit.text = logTextEdit.text.slice(logTextEdit.text.indexOf('\n')+2)
logTextEdit.linesTrimmed++
}
logTextEdit.insert(0, "[... trimmed " + logTextEdit.linesTrimmed + " lines ...]\n")
}
}
}
I picked a ScrollView as I'd like to have the vertical scroll bar. Lines are added one at a time by the C++ code, when it emits the newMessageLineAdded signal. This is coming from a class which includes this Q_PROPERTY, used to pass the new line content:
Q_PROPERTY(QString newMessageLine READ newMessageLine NOTIFY newMessageLineAdded)
the signal is declared as:
void newMessageLineAdded();
I have added the small bit of java to trim the log when it grows too long, as the issue is there even when this trimming code is not present.
Am I doing something very clunky here? Should I use another type of object to replace the TextEdit, knowing that it is not used at all to edit text, but only as a display?
Thanks.
I recommend you to use ListView instead of TextEdit. And use QStringListModel as model declared in C++ code and added to QML as context property. Read Embedding C++ Objects into QML with Context Properties. It is recommended for better perfomance to have most of logic in C++ code.

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.

Resources