Qt Creator compile error for QSensor - qt

I'm new to Qt/Symbian development (I come from an iOS background), and I can't make sense of this compiler error:
Firstly, this is the error I'm getting:
/Users/Dave/AR-build-simulator/../QtSDK/Simulator/QtMobility/gcc/include/QtSensors/qsensor.h:-1: In member function 'QtMobility::QMagnetometerReading& QtMobility::QMagnetometerReading::operator=(const QtMobility::QMagnetometerReading&)':
Here is my header file:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui/QMainWindow>
#include <QSystemDeviceInfo>
#include <QGeoPositionInfoSource>
#include <QGeoCoordinate>
#include <QGeoPositionInfo>
#include <QMagnetometer>
QTM_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
enum ScreenOrientation {
ScreenOrientationLockPortrait,
ScreenOrientationLockLandscape,
ScreenOrientationAuto
};
explicit MainWindow(QWidget *parent = 0);
virtual ~MainWindow();
// Note that this will only have an effect on Symbian and Fremantle.
void setOrientation(ScreenOrientation orientation);
void showExpanded();
private slots:
void positionUpdated(QGeoPositionInfo gpsPos);
void magnetometerReadingChanged(QMagnetometerReading mr);
private:
Ui::MainWindow *ui;
void setupGeneral();
QGeoPositionInfoSource *m_location;
QGeoCoordinate m_coordinate;
QMagnetometer *m_magnetometer;
QMagnetometerReading m_magnetometerReading;
};
#endif // MAINWINDOW_H
Here is the implementation file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore/QCoreApplication>
#include <qgeopositioninfosource.h>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
setupGeneral();
}
void MainWindow::setupGeneral()
{
m_location = QGeoPositionInfoSource::createDefaultSource(this);
//Listen to gps position changes
QObject::connect(m_location, SIGNAL(positionUpdated(QGeoPositionInfo)), this,SLOT(positionUpdated(QGeoPositionInfo)));
//Start listening to GPS position updates
m_location->startUpdates();
//Start listening to magnetometer updates
m_magnetometer = new QMagnetometer(this);
connect(m_magnetometer, SIGNAL(readingChanged(QMagnetometerReading)), this, SLOT(magnetometerReadingChanged(QMagnetometerReading)));
m_magnetometer->start();
}
void MainWindow::positionUpdated(QGeoPositionInfo gpsPos){
m_coordinate = gpsPos.coordinate();
if (m_coordinate.isValid()) {
m_location->stopUpdates();
QString longitude;
QString latitude;
longitude.setNum(m_coordinate.longitude());
latitude.setNum(m_coordinate.latitude());
QMessageBox::information(this,"latitude",latitude);
} else {
QMessageBox::information(this, "GPS Info", "Coordinator is not valid...");
}
}
void MainWindow::magnetometerReadingChanged(QMagnetometerReading mr) {
QMessageBox::information(this, "Magnetometer info", "got magnetometer reading...");
m_magnetometerReading = mr;
//m_magnetometerReading = new QMagnetometerReading(this);
//m_magnetometerReading->copyValuesFrom(mr);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setOrientation(ScreenOrientation orientation)
{
#if defined(Q_OS_SYMBIAN)
// If the version of Qt on the device is < 4.7.2, that attribute won't work
if (orientation != ScreenOrientationAuto) {
const QStringList v = QString::fromAscii(qVersion()).split(QLatin1Char('.'));
if (v.count() == 3 && (v.at(0).toInt() << 16 | v.at(1).toInt() << 8 | v.at(2).toInt()) < 0x040702) {
qWarning("Screen orientation locking only supported with Qt 4.7.2 and above");
return;
}
}
#endif // Q_OS_SYMBIAN
Qt::WidgetAttribute attribute;
switch (orientation) {
#if QT_VERSION < 0x040702
// Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
case ScreenOrientationLockPortrait:
attribute = static_cast<Qt::WidgetAttribute>(128);
break;
case ScreenOrientationLockLandscape:
attribute = static_cast<Qt::WidgetAttribute>(129);
break;
default:
case ScreenOrientationAuto:
attribute = static_cast<Qt::WidgetAttribute>(130);
break;
#else // QT_VERSION < 0x040702
case ScreenOrientationLockPortrait:
attribute = Qt::WA_LockPortraitOrientation;
break;
case ScreenOrientationLockLandscape:
attribute = Qt::WA_LockLandscapeOrientation;
break;
default:
case ScreenOrientationAuto:
attribute = Qt::WA_AutoOrientation;
break;
#endif // QT_VERSION < 0x040702
};
setAttribute(attribute, true);
}
void MainWindow::showExpanded()
{
#ifdef Q_OS_SYMBIAN
showFullScreen();
#elif defined(Q_WS_MAEMO_5)
showMaximized();
#else
show();
#endif
}
If anybody could explain to me what is going wrong, I'd be very grateful.

According to the documentation(here) readingChanged signal does not have any parameters. You should use
connect(m_magnetometer, SIGNAL(readingChanged()), this, SLOT(magnetometerReadingChanged())); and then acquire the reading from the reading property.

Related

Color channels are changing using Qt QImage with data and I don't know why

I have written a function in Qt to extract the data out of an image for the purpose of manipulating it.
I then have another function to reinsert the data back to an image and display it. The problem I am having is that even if I do no manipulation on the pixel data other than extract and reinsert, it is still changing the data. On a yellow image it changes it to turquoise blue when it should remain yellow.
I am including the function code to extract and reinsert as specimen code. I can include more if it is needed such as the display function etc...Does anyone know if I am doing something wrong?
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
filter = "All Picture Files (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"
";; Bitmap Files (*.bmp) ;; JPEG (*.jpg *.jpeg) ;; PNG (*.png) ;; TIFF (*.tif *.tiff)";
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::importImage()
{
importCancelled = false;
QString filename = QFileDialog::getOpenFileName(nullptr, QObject::tr("Import Image"), "", filter);
if(!filename.isEmpty()){
image.load(filename);
image = image.convertToFormat(QImage::Format_RGBA8888);
}
else {
importCancelled = true;
if(importCancelled){
QString cleanPlateCancelled = "Operation Cancelled";
ui->statusBar->showMessage(cleanPlateCancelled,5000);
return;
}
}
}
void MainWindow::scaleImage()
{
if (image.isNull()){
return;
}
else {
image = image.scaledToHeight(ui->view->height(), Qt::TransformationMode::SmoothTransformation);
}
}
void MainWindow::displayImage()
{
if (image.isNull()){
return;
}
else {
scene = new QGraphicsScene;
showImage = new QGraphicsPixmapItem(QPixmap::fromImage(image));
scene->addItem(showImage);
ui->view->setScene(scene);
}
}
void MainWindow::rgbaExtraction()
{
numberOfBytes = static_cast<uint>(image.sizeInBytes());
auto const imageData = image.bits();
rgba = std::vector<uchar>(numberOfBytes,0);
rgbaReset = std::vector<uchar>(numberOfBytes,0);
for (uint i{0}; i < numberOfBytes; ++i) {
rgbaReset[i] = rgba[i] = imageData[i];
}
}
void MainWindow::rgbaInsertion()
{
auto *imageData = new uchar[numberOfBytes];
for (uint i{0};i < numberOfBytes;++i) {
imageData[i] = rgba[i];
}
image = QImage(imageData, image.width(), image.height(), QImage::Format_RGBA8888);
}
void MainWindow::on_importButton_clicked()
{
importImage();
scaleImage();
displayImage();
rgbaExtraction();
}
void MainWindow::on_quitButton_clicked()
{
QApplication::quit();
}
void MainWindow::sceneUpdater()
{
showImage->setPixmap(QPixmap::fromImage(image));
scene->update();
ui->view->update();
}
void MainWindow::on_redSlider_valueChanged(int value)
{
QString redString = QString::number(value);
ui->redLabel->setText(redString);
redDelta = value;
colorRed();
rgbaInsertion();
sceneUpdater();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QImage>
#include <QFileDialog>
#include <string>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_importButton_clicked();
void on_quitButton_clicked();
void on_redSlider_valueChanged(int value);
private:
QGraphicsPixmapItem *showImage;
QGraphicsScene *scene;
QString filter;
QImage image;
bool importCancelled;
QStatusBar *statusBar;
uint numberOfBytes;
std::vector<uchar> rgba;
std::vector<uchar> rgbaReset;
int redDelta{0};
int greenDelta{0};
int blueDelta{0};
int opacityDelta{0};
void importImage();
void scaleImage();
void displayImage();
void rgbaExtraction();
void rgbaInsertion();
void sceneUpdater();
void colorRed(); // Implemented in color.cpp
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
color.cpp
#include <mainwindow.h>
void MainWindow::colorRed()
{
for (uint i{0}; i < rgba.size()*sizeof (rgba[i]);i+=4) {
if(rgbaReset[i] + static_cast<uchar>(redDelta)>=255){
rgba[i] = 255;
}
else {
rgba[i] = rgbaReset[i];// + static_cast<uchar>(redDelta);
}
}
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
The problem is in scaleImage(), because scaledToHeight() returns another image format. You may omit the scale operation, or convert the returned image to Format_RGBA8888:
void MainWindow::scaleImage()
{
if (image.isNull()){
return;
}
else {
image = image.scaledToHeight(ui->view->height(), Qt::TransformationMode::SmoothTransformation)
.convertToFormat(QImage::Format_RGBA8888);
}
}
My recomendation is to add some instrumentation after each image manipulation to check that it has the expected format:
qDebug() << Q_FUNC_INFO << "image format:" << image.format();

How to save recordings to *.wav?

I trying to change my code to save recordings to wav-files. Later i have to import this to MATLAB.
Its works to save like .*pcm or.*wav. But I want play it with (example VLC Player) external player.
QAudioFormat format;
Conf values;
format.setSampleRate(values.getSampRate());
format.setChannelCount(values.getChannel());
format.setSampleSize(values.getSampSize());
format.setCodec(values.getCodec());
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
in config-file i have configuration:
samp_rate=88200
channel=1
samp_size=24
codec=Audio/PCM
byte_order=QAudioFormat::LittleEndian
sample_type=QAudioFormat::SignedInt
Saving file looks:
m_audio->startrecording(fn+".pcm");
I changed pcm to wav - file will be recorded, but I cant open it with VLC (just import to Audacity with manual input of sample Rate, ByteOrder). Its because of RAW-data? how can able to save my recording like wav-file included sample-size, sampl-rate ...?
Audio.cpp
// ************************************************************************************************
// Audio-Class
// ************************************************************************************************
#include "Audio.h"
#include "Conf.h"
#include "Measure.h"
// ************************************************************************************************
Audio::Audio(Conf *conf)
{
m_conf = conf;
AudioRecord();
}
// ************************************************************************************************
//Initialization and signal-slot connection
void Audio::AudioRecord()
{
QAudioFormat format;
Conf values;
format.setSampleRate(values.getSampRate());
format.setChannelCount(values.getChannel());
format.setSampleSize(values.getSampSize());
format.setCodec(values.getCodec());
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
if (!info.isFormatSupported(format))
{
qWarning() << "Default format not supported";
format = info.nearestFormat(format);
}
m_audio = new QAudioInput(format, this);
connect(m_audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State)));
}
// ************************************************************************************************
//Start recording method
void Audio::startrecording(QString rec_file_path)
{
m_file.setFileName(rec_file_path);
m_file.open(QIODevice::WriteOnly);
m_audio->start(&m_file);
}
// ************************************************************************************************
//Stop recording
void Audio::stoprecording()
{
m_audio->stop();
m_file.close();
}
// ************************************************************************************************
//Recording DEBUG output
void Audio::handleStateChanged(QAudio::State newState)
{
switch (newState)
{
case QAudio::StoppedState:
if (m_audio->error() != QAudio::NoError)
{
qDebug() << "Error!!";
} else
{
qDebug() << "Finished recording";
}
break;
case QAudio::ActiveState:
qDebug() << "Started recording";
break;
default:
break;
}
}
// ************************************************************************************************
Audio.h
// ************************************************************************************************
// Audio-HEADER-file
// ************************************************************************************************
#ifndef AUDIO_H
#define AUDIO_H
// ************************************************************************************************
// Includes
#include <QDebug>
#include <QObject>
#include "Conf.h"
#include <QAudioInput>
#include <QDateTime>
#include <QTimer>
// ************************************************************************************************
// Define
#define SAVE_AUDIO_PATH "/home/nikitajarocky/workspace/QT/UART_PC/IO/"
// ************************************************************************************************
// Class variables and methods
class Audio : public QObject
{
Q_OBJECT
public:
explicit Audio(Conf *conf);
void start(QString file_name);
void stop();
void startrecording(QString);
void stoprecording();
signals:
public slots:
void handleStateChanged(QAudio::State);
void AudioRecord();
private:
Conf *m_conf;
Conf *m_samp_rate;
QAudioInput *m_audio;
QFile m_file;
};
// ************************************************************************************************
#endif // AUDIO_H
A much simpler approach is use QAudioRecorder, it handles the writing of the header and also handles the audio capture.
It saves you from big changes, if your goal is only recording.
See the example:
audio.h:
#ifndef AUDIO_H
#define AUDIO_H
#include <QtCore>
#include <QtMultimedia>
class Audio : public QObject
{
Q_OBJECT
public:
explicit Audio(QObject *parent = nullptr);
~Audio();
public slots:
QStringList audioInputs();
bool record(const QString &path, const QString &audio_input = QString());
void stop();
private:
QAudioRecorder *m_recorder;
};
#endif // AUDIO_H
audio.cpp:
#include "audio.h"
Audio::Audio(QObject *parent) : QObject(parent)
{
m_recorder = new QAudioRecorder(this);
}
Audio::~Audio()
{
stop();
}
QStringList Audio::audioInputs()
{
return m_recorder->audioInputs();
}
bool Audio::record(const QString &path, const QString &audio_input)
{
QAudioEncoderSettings audio_settings;
audio_settings.setCodec("audio/pcm");
audio_settings.setChannelCount(1);
audio_settings.setSampleRate(44100);
m_recorder->setEncodingSettings(audio_settings);
m_recorder->setOutputLocation(path);
m_recorder->setAudioInput(audio_input);
m_recorder->record();
if (m_recorder->state() == QAudioRecorder::RecordingState)
{
qDebug() << "Recording...";
return true;
}
else
{
qDebug() << qPrintable(m_recorder->errorString());
return false;
}
}
void Audio::stop()
{
if (m_recorder->state() == QAudioRecorder::RecordingState)
{
m_recorder->stop();
qDebug() << "Recording stopped";
}
else
{
qDebug() << "Nothing to stop";
}
}
Usage example (recording 5 seconds):
#include <QtCore>
#include "audio.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Audio audio;
audio.record("file.wav");
QTimer::singleShot(5 * 1000, &audio, &Audio::stop);
return a.exec();
}

Qt: how to apply a 2-step key shortcut to action

I know how to apply a keyboard shortcut to an action. And in some software such as Visual Studio there are shortcuts that do the job in more than one step (such as Ctrl+K,Ctrl+C to comment the code).
Another example of that in Sublime Text:
I wonder whether or not it is possible to implement in Qt.
You can create it by using the multiple arguments constructor for QKeySequence.
like this:
auto ac = new QAction(this);
ac->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_K, Qt::CTRL + Qt::Key_C));
Try this:
action->setShortcut("Ctrl+K,Ctrl+C");
QKeySequence may be implicitly created from QString.
Due to documentation:
Up to four key codes may be entered by separating them with commas, e.g. "Alt+X,Ctrl+S,Q".
MOC generates almost same code when you create shortcut for a QAction via Qt Designer. But it makes it slightly different:
action->setShortcut(QApplication::translate("MainWindow", "Ctrl+K, Ctrl+C", 0));
but it's actually same thing.
You can use eventFilter to get mouse & keyboard events.
I use boolean to get first and second key, Ctrl + K then C.
I made you a sample code it's working.
.cpp file:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
firstKey = false;
secondKey = false;
this->installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
if (object == this &&event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if ((keyEvent->key() == Qt::Key_Control))
{
firstKey = true;
return true;
}
else if ((keyEvent->key() == Qt::Key_K))
{
secondKey = true;
return true;
}
else if ((keyEvent->key() == Qt::Key_C))
{
if(firstKey && secondKey)
{
firstKey = false;
secondKey = false;
QMessageBox::information(this, "", "Ctrl + k + c");
}
return true;
}
else
return false;
}
else
return false;
}
void MainWindow::keyReleaseEvent(QKeyEvent *e)
{
if (e->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
if ((keyEvent->key() == Qt::Key_Control))
{
firstKey = false;
}
}
}
.h file:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QMessageBox>
#include <QKeyEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
bool firstKey;
bool secondKey;
bool eventFilter(QObject *object, QEvent *event);
void keyReleaseEvent(QKeyEvent *e);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

QLineEdit: controlling the input validation while the input is being provided

I need to control the input that is being provided through a QLineEdit. The provided input will be checked to see if it meets certain criteria (i.e. particular letters, digits and symbols constraints)
Tasks:
This checking procedure has to be done when the user is providing input.
Due to the mismatch with the constraint list, a message should pop-up to notify the user.
My Problem: I only can see how to check the text after the user presses any pushbutton while my goal is to check the input while it is being provided and not have to wait until the button is pressed.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QString>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString reg_exp("!§$%&/(){}[]=?\ß`*+~#'.,;-#");
int flag = 0;
QString str = ui->lineEdit->text();
for(int i = 0; i < str.length(); ++i)
{
for(int j = 0; j < reg_exp.length(); ++j )
{
if(str[i] == reg_exp[j])
flag = 1;
}
if (flag == 1)
{
QMessageBox::warning(this,"Check","Its a mismatch!");
break;
}
}
}
You can use the QLineEdit::textEdited signal: create a slot for it, and then put the contents of your function MainWindow::on_pushButton_clicked in the new slot function (by default this would be MainWindow::on_lineEdit_textEdited(const QString &arg1)).
Here is the finised code, but in a very simple version. I have not used any regular expression validation.
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_lineEdit_textEdited(const QString &str);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->lineEdit,static_cast<void (QLineEdit::*)(const QString&)>(&QLineEdit::textEdited),this,&MainWindow::on_lineEdit_textEdited);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_lineEdit_textEdited(const QString &str)
{
int flag = 0;
for(int i = 0; i < str.length(); ++i)
{
if((str[i] >= 'A') && (str[i] <= 'Z') || (str[i] >= 'a') && (str[i] <= 'z') || (str[i] == '_') || (str[i] >= '0') && (str[i] <= '9') )
{
ui->lineEdit->setStyleSheet("QLineEdit{border: 2px solid green}");
}
else
{
ui->lineEdit->setStyleSheet("QLineEdit{border: 2px solid red}");
flag = 1;
break;
}
}
if(flag == 1)
QMessageBox::warning(this,"Check","Wrong Input!");
}

Get duration of QMediaPlaylist object

I create a player for audiobooks - when you open a folder with mp3 file, whole list of them is added to playlist and List View. And i have a Label, which suppose to show duration of the whole book. But player->duration returns only a duration of current track, and if i go through the loop and do playlist->next() every step, player->duration returns 0. I know about Phonon and file metadata, but i need to do this without using it.
I am attaching a source code of a working project, you can use. When the player changes the file, the duration is changed and printed out. To loop within files, there is a need to wait till the decoder completes reading the media file. See the code below and the comments.
This is mainwindow.cpp
#include "mainwindow.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
bool done =false;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
player = new QMediaPlayer(this);
playlist = new QMediaPlaylist(player);
playlist->setPlaybackMode(QMediaPlaylist::Sequential);
player->setPlaylist(playlist);
connect(player, &QMediaPlayer::durationChanged, this, &MainWindow::on_durationchanged);
//connect(player,&QMediaPlayer::)
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
playlist->addMedia(QUrl::fromLocalFile("Ar_today.mp3"));
playlist->addMedia(QUrl::fromLocalFile("Ar_sunday.mp3"));
playlist->setCurrentIndex(0); //set the first file
while (done == false) //wait till the duration is read
{
QApplication::processEvents();
}
done = false; playlist->setCurrentIndex(1); //change to the second file
while (done == false) //wait till the duration is read
{
QApplication::processEvents();
} //this way you can loop through files
player->setVolume(80);
player->play();
qDebug() << player->errorString();
}
void MainWindow::on_pushButton_2_clicked()
{
player->stop();
}
void MainWindow::on_durationchanged(qint64 duration)
{
done = true;
qDebug() << "duration = " << player->duration();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QDebug>
extern bool done;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_durationchanged(qint64 duration);
private:
Ui::MainWindow *ui;
QMediaPlayer* player;
QMediaPlaylist* playlist;
};
#endif // MAINWINDOW_H
In the form, create 2 buttons, one called pushbutton to play and the other is pushButton_2 to stop

Resources