c++ - 以第二种形式使用 QMediaPlayer

标签 c++ qt linux-mint

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

主要.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();
}

对话框.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();

关于c++ - 以第二种形式使用 QMediaPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39266244/

相关文章:

c++ - 带/不带虚拟的纯虚拟方法的实现?

c++ - C++ 中的构造函数初始化有什么区别?

c++ - 函数指针返回不同的类类型

image - Qt-OpenCV :How to display grayscale images(opencv) in Qt

c - Bind() 在我的机器上返回 -1,而在其他机器上运行正常

c++ - ABC 中的多态静态常量成员变量?

c++ - 在 Qt TableView 中更改数据

c++ - 如何在 Qt Designer 中为自定义插件的 QString 属性删除 "translatable"复选框?

linux - 如何重置所有环境变量?

linux - Mint - 存储的 SVN 密码已更改,现在无法提交