adjust brightness of led using QSlider and PWM in arduino - qt

i try to control the brightness of the led with QSlider qt ui.i was facing issue which is led not turn on with the slider value. i think it has taken value like 123456... then i tried solution which is add some separator.. parseInt() stops on any not digit character. now i am facing the issue that led is turning on properly with pwm value which is passed from slider but it is turning off automatically after one second.
here is my qt code.
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <string>
#include <QDebug>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QRegularExpression>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
arduino = new QSerialPort(this);
bool is_arduino_avilable = false;
QString portNmae;
databuf = "";
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
if(info.hasProductIdentifier() && info.hasVendorIdentifier())
{
if(info.productIdentifier() == arduino_productId && info.vendorIdentifier() == arduino_vendorId)
{
is_arduino_avilable = true;
portNmae = info.portName();
}
}
}
if(is_arduino_avilable)
{
qDebug() << "Arduino port is found " + portNmae;
arduino->setPortName(portNmae);
arduino->open(QSerialPort::ReadWrite);
arduino->setBaudRate(QSerialPort::Baud9600);
arduino->setDataBits(QSerialPort::Data8);
arduino->setFlowControl(QSerialPort::NoFlowControl);
arduino->setParity(QSerialPort::NoParity);
arduino->setStopBits(QSerialPort::OneStop);
QObject::connect(arduino,SIGNAL(readyRead()),this,SLOT(readSerialdata()));
}
else
{
qDebug() << "Couldn't find the correct port for the arduino.\n";
QMessageBox::information(this,"Serial Port Error","Couldn't open serial port to arduino");
}
}
MainWindow::~MainWindow()
{
if(arduino->isOpen())
{
arduino->close();
}
delete ui;
}
void MainWindow::on_pluse_slider_valueChanged(int value)
{
ui->slider_value->setText(QString("<span style=\"font-size:14pt; font-weight:600;\">%1</span>").arg(value));
qDebug()<<value;
arduino->write(QString("%1").arg(value).toStdString().c_str());
}
and here is my arduino code.
pwm.ino
const int LED = 11;
int rsv_data;
void setup()
{
Serial.begin(9600);
pinMode(LED,OUTPUT);
}
void loop()
{
if(Serial.available())
{
rsv_data = Serial.parseInt();
analogWrite(LED,rsv_data);
}
}
Thank you in advance.
this is ui image
this is debug output image

i have solved this issue using below solution:
i have added the comma(,) as separator befor the value in this below line arduino>write(QString(",%1").arg(val).toStdString().c_str());
this line is in this function void MainWindow::on_pluse_slider_valueChanged(int value)

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

connecting a signal of widget in a plasmoid

I am new to Qt and am trying to connect the cilicked signal o a push button with a function hile writing a plasmoid. I am trying to use an external function as a public with Plasma::PushButton type object so that I can use it to connect it with the clicked signal? With gtk it was as simple as on_...._clicked do this but isnt there a simple way in qt, where we can do away with the need to use slots?
#include "plasma-tutorial1.h"
#include<string.h>
#include <stdlib.h>
#include <QGraphicsLinearLayout>
#include <QPainter>
#include <QFontMetrics>
#include <QSizeF>
#include <QTextEdit>
#include <plasma/svg.h>
#include <plasma/theme.h>
#include <plasma/widgets/lineedit.h>
#include <plasma/widgets/pushbutton.h>
#include <plasma/widgets/textedit.h>
//PlasmaTutorial1 mainf;
themainfunction(int choice,Plasma::LineEdit *m_lineEdit,
Plasma::TextEdit *m_displaytext)
{
char buffer[100];
const char *inp=(const char *)malloc(sizeof(char)*100);
QString input;
input=m_lineEdit->text();
QByteArray byteArray = input.toUtf8();
inp = byteArray.constData();
char *expression;
expression=(char *)malloc(sizeof(char)*100);
strcpy(expression,"sudo apt-");
switch(choice)
{
case 1:{
strcat(expression,"get install ");
strcat(expression,inp);
break;
};
case 2:{
strcat(expression,"get remove ");
strcat(expression,inp);
break;
};
case 3:{
strcat(expression,"cache search ");
strcat(expression,inp);
break;
};
};
/*
FILE* in;
FILE* ptr=fopen("new.txt","w");
FILE *popen();
if(!(in = popen("cal","r")))
{return;}
while(fgets(buffer, 100, in) != NULL) {
*/
m_displaytext->append("yeah!");
// fprintf(ptr,"%s",buffer);
//}
//pclose(in);
//fclose(ptr);
}
PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args)
: Plasma::Applet(parent, args),
m_svg(this),
m_icon("document")
{
m_svg.setImagePath("widgets/background");
// this will get us the standard applet background, for free!
setBackgroundHints(DefaultBackground);
resize(200, 200);
}
PlasmaTutorial1::~PlasmaTutorial1()
{
if (hasFailedToLaunch()) {
// Do some cleanup here
} else {
// Save settings
}
}
void PlasmaTutorial1::init()
{
/* // A small demonstration of the setFailedToLaunch function
if (m_icon.isNull()) {
setFailedToLaunch(true, "No world to say hello");
}*/
Counter rt;
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(this);
layout->setOrientation(Qt::Vertical); //so widgets will be stacked up/down
m_lineEdit = new Plasma::LineEdit(this);
m_lineEdit->setText("Enter the package name here");
m_displaytext = new Plasma::TextEdit(this);
m_displaytext->setText("Terminal");
m_installButton = new Plasma::PushButton(this);
m_installButton->setText("Install");
connect(m_installButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(1,m_lineEdit,m_displaytext)));
m_removeButton = new Plasma::PushButton(this);
m_removeButton->setText("Remove");
// m_removeButton->clicked()
connect(m_removeButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(2,m_lineEdit,m_displaytext)));
m_searchButton = new Plasma::PushButton(this);
m_searchButton->setText("Search");
connect(m_searchButton, SIGNAL(clicked()),&rt,SLOT(themainfunction(3,m_lineEdit,m_displaytext)));
layout->addItem(m_lineEdit);
layout->addItem(m_installButton);
layout->addItem(m_removeButton);
layout->addItem(m_searchButton);
layout->addItem(m_displaytext);
m_displaytext->append("yo baby!");
}
/*
void PlasmaTutorial1::paintInterface(QPainter *p,
const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
p->setRenderHint(QPainter::SmoothPixmapTransform);
p->setRenderHint(QPainter::Antialiasing);
// Now we draw the applet, starting with our svg
m_svg.resize((int)contentsRect.width(), (int)contentsRect.height());
m_svg.paint(p, (int)contentsRect.left(), (int)contentsRect.top());
// We place the icon and text
p->drawPixmap(7, 0, m_icon.pixmap((int)contentsRect.width(),(int)contentsRect.width()-14));
p->save();
p->setPen(Qt::white);
p->drawText(contentsRect,
Qt::AlignBottom | Qt::AlignHCenter,
"Hello Plasmoid!");
p->restore();
}
*/
// This is the command that links your applet to the .desktop file
K_EXPORT_PLASMA_APPLET(tutorial1, PlasmaTutorial1)
#include "plasma-tutorial1.moc"
say i want to connect themainfunction() upon clicked signal of install button . how do i do it? how can I derive a class in plasma?
i got where was i missing out. We cannot pass objects as arguments in slot functions. Now it is running smooth. thanx for all your replies.

Qt Creator compile error for QSensor

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.

how to calculate speed by gps data in qt mobility?

How I can get my speed, and distance by using gps data in qt?
I have such class, maybe is any standart method?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "quitdiallog.h"
#include <QGeoCoordinate>
#include <QDebug>
#include <QtGui/QMessageBox>
#include <QList>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
setWindowTitle("Мой кОмпаС");
ui->setupUi(this);
startGPS();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::startGPS()
{
// Obtain the location data source if it is not obtained already
if (!locationDataSource)
{
locationDataSource =
QGeoPositionInfoSource::createDefaultSource(this);
if (locationDataSource)
{
// Whenever the location data source signals that the current
// position is updated, the positionUpdated function is called.
QObject::connect(locationDataSource,
SIGNAL(positionUpdated(QGeoPositionInfo)),
this,
SLOT(positionUpdated(QGeoPositionInfo)));
// Start listening for position updates
locationDataSource->setUpdateInterval(200);
locationDataSource->startUpdates();
} else {
// Not able to obtain the location data source
// TODO: Error handling
}
} else {
// Start listening for position updates
locationDataSource->setUpdateInterval(5000);
locationDataSource->startUpdates();
}
}
void MainWindow::positionUpdated(QGeoPositionInfo geoPositionInfo)
{
if (geoPositionInfo.isValid())
{
//locationDataSource->stopUpdates();
QGeoCoordinate geoCoordinate = geoPositionInfo.coordinate();
this->latitude = geoCoordinate.latitude();
this->longitude = geoCoordinate.longitude();
this->altitude=geoCoordinate.altitude();
ui->label->setNum(latitude);
ui->label_2->setNum(longitude);
}
}
void MainWindow::on_pushButton_clicked()
{
ui->label_3->setNum(latitude);
qDebug()<<latitude<<" "<<longitude<<" "<<altitude;
}
void MainWindow::on_pushButton_4_clicked()
{
QuitDiallog *qi=new QuitDiallog;
this->hide();
qi->show();
}
How to get speed???
first i would do source->setPreferredPositioningMethods(QGeoPositionInfoSource::AllPositioningMethods);
The groundspeed can be fetched (theoretically) by geoPositionInfo.attribute(QGeoPositionInfo::GroundSpeed)
But be sure that geoPositionInfo.hasAttribute(QGeoPositionInfo::GroundSpeed) == true
AFAIK there are some issues with groundspeed on several mobile devices.

Resources