Search code examples
c++qtlinux-mint

Using QMediaPlayer in second form


I am newbie at Qt. I have a problem with QMediaPlayer: my program has 2 forms (main form and for notice). So it has condition and if it's true, program must show second form and play music on load form.

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include "dialog.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    Dialog d;
    d.musicPlay();
    d.show();


    return a.exec();
}

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"
#include <QMediaPlayer>
#include <QUrl>
#include <QDebug>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    uix(new Ui::Dialog)
{
    uix->setupUi(this);
}

void Dialog::musicPlay() const
{
    QMediaPlayer pl;
    pl.setMedia(QUrl::fromLocalFile("/home/jack/01.mp3"));
    pl.setVolume(100);
    pl.play();
    qDebug()<<pl.errorString();
}

Dialog::~Dialog()
{
    delete uix;
}

It does not work, but if musicPlay() would be like:

uix->label->setText("qwerty");

it would work. Can you help to solve this problem? Maybe I must use slots and signals?


Solution

  • This doesn't work because you have declared the pl variable as a local variable being saved in the stack. Stack variables will be destroyed opon finishing the function.

    So, you should declare and define the pl using new keyword.

    QMediaPlayer* pl = new QMediaPlayer;
    pl->setMedia(QUrl::fromLocalFile("/home/jack/01.mp3"));
    pl->setVolume(100);
    pl->play();