以第二种形式使用 QMediaPlayer

Using QMediaPlayer in second form

我是 Qt 的新手。我对 QMediaPlayer 有疑问:我的程序有 2 种形式(主要形式和通知形式)。所以它有条件,如果它是真的,程序必须显示第二种形式并在加载形式上播放音乐。

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;
}

它不起作用,但如果 musicPlay() 会像:

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

它会起作用的。 你能帮忙解决这个问题吗?也许我必须使用插槽和信号?

这不起作用,因为您已将 pl 变量声明为保存在堆栈中的局部变量。堆栈变量将在函数完成时被销毁。

因此,您应该使用 new 关键字声明和定义 pl

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