Problems not create Can Bus Device, create project Qt 5.10 why not create ??
package serialbus be connected. CAN be connected across USB. IIts so hard. My life its harded. I'm a national minority, I'm not as clever as white masters, please do not grieve for me.
can bus Device not working
file.pro
QT += core gui serialbus
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = CAN_simple_experiment
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtSerialBus>
#include <QCanBus>
#include <QCanBusDevice>
#include <QDebug>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
int i = 0;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
// Create device.
QCanBusDevice *device =
QCanBus::instance()>createDevice("socketcan","vcan0");
if (device != nullptr){
qDebug() << "Created device, state is:" << device->state();
ui->textEdit->append("Created device, state is:"+ device->state());
} else {
qFatal("Unable to create CAN device.");
ui->textEdit->append("Unable to create CAN device.");
}
//Connect.
if(device->connectDevice()){
qDebug() << "Connected, state is:" << device->state();
ui->textEdit->append("Connected, state is:"+ device->state());
} else {
qDebug() << "Connect failed, error is:" << device->errorString();
ui->textEdit->append("Connect failed, error is:"+ device->errorString());
}
}
You need first to check SocketCAN interfaces that can be used check documentation.
QString errorString;
const QList<QCanBusDeviceInfo> devices = QCanBus::instance()->availableDevices(
QStringLiteral("socketcan"), &errorString);
if (!errorString.isEmpty())
qDebug() << errorString;
You can't create the device if the list is empty (watch the errorString);
// Create device.
if (devices.count())
QCanBusDevice *device =
QCanBus::instance()>createDevice("socketcan","vcan0");
There is no support of socketcan on Windows.
There are Linux specific calls inside socketcanbackend.cpp:
#include <linux/can/error.h>
#include <linux/can/raw.h>
#include <linux/sockios.h>
...
if (Q_UNLIKELY(ioctl(canSocket, SIOCGSTAMP, &timeStamp) < 0)) {
...
etc
Related
Env: Win10+Qt5.12.3(msvc)
code:
pro:
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = test
TEMPLATE = app
SOURCES += \
dialog.cpp \
main.cpp \
mainwindow.cpp
HEADERS += \
dialog.h \
mainwindow.h
FORMS += \
dialog.ui \
mainwindow.ui
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDialog>
#include "dialog.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void slot_btn_clicked();
private:
Ui::MainWindow *ui;
Dialog *dialog;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
dialog = new Dialog(this);
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(slot_btn_clicked()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::slot_btn_clicked()
{
dialog->exec();
}
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QCloseEvent>
#include <QShowEvent>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
protected:
void closeEvent(QCloseEvent *e);
public:
explicit Dialog(QWidget *parent = nullptr);
~Dialog();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
Dialog::Dialog(QWidget *parent)
: QDialog(parent), ui(new Ui::Dialog)
{
ui->setupUi(this);
QVBoxLayout *layout = new QVBoxLayout(this);
QLabel *label = new QLabel(this);
label->setText("this is a label");
layout->addWidget(label);
QPushButton *btnaccept= new QPushButton(this);
btnaccept->setText("accept");
connect(btnaccept, &QPushButton::clicked, this, [=](){accept();});
layout->addWidget(btnaccept);
QPushButton *btnclose= new QPushButton(this);
btnclose->setText("close");
connect(btnclose, &QPushButton::clicked, this, [=](){close();});
layout->addWidget(btnclose);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::closeEvent(QCloseEvent *e)
{
qDebug() << __FUNCTION__;
QDialog::closeEvent(e);
//e->ignore(); // if ignored close event, working well.
//accept();
}
demo code pack
Video presentation
I found that a method of closing QDialog will cause this situation: close button in title bar(top-right corner of the dialog), if closing it by reject(), accept(), close() everything is working correctly.
There is another question which is similar with mine, but I think the answer (resize the dialog manually) is not perfect, is there any another solution?
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
I observed that through task mgr, the memory increases in steps of 4kB and 8kB, though not necessarily in this order.
Possible duplicate: Windows Task Manager shows process memory keeps growing even though there are no memory leaks
I am not sure whether this's occurring because I did not release the QTimer object, timer2. Please advise me how to stop this memory increase, and whether my guess of why it's occurring, is correct.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCore>
#include <QDebug>
#include <QDateTime>
#include <QFileInfo>
#include <QString>
#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#define TIMER2_VALUE 3000
#define UPDATED_IMAGE_STORAGE_PATH "E:\\QT1\\timeStampDateMod2\\TimeStampDateMod2\\updatedRefImg.JPG"
#define UPDATED_IMAGE_BACKUP_PATH "E:\\QT1\\timeStampDateMod2\\TimeStampDateMod2\\backUp\\updatedRefImg[%1].JPG"
using namespace std;
using namespace cv;
typedef struct
{
QDateTime dateTimeMod1;
QDateTime dateTimeMod2;
}tTimeMods;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QTimer *timer2;
tTimeMods findTimeModifiedStruct();
QDateTime findTimeModified();
void compareTimeMods(tTimeMods timeTypeFunction, QDateTime dateTimeMod2);
QString appendWithImageName(tTimeMods timeTypeFunction);
void shiftToRepository(QString pathString);
void updatedImgToRepository(QString pathString);
public slots:
void timerSlot2();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
tTimeMods timeTypeFunction, timeTypeMain;
QDateTime dateTimeMod2;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timeTypeMain = findTimeModifiedStruct();
timer2 = new QTimer(this);
connect(timer2, SIGNAL(timeout()), this, SLOT(timerSlot2()));
timer2->start(TIMER2_VALUE);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::timerSlot2()
{
dateTimeMod2 = findTimeModified();
compareTimeMods(timeTypeMain, dateTimeMod2);
//delete timer2;
}
//tTimeMods findTimeModifiedStruct()
tTimeMods MainWindow::findTimeModifiedStruct()
{
QString myFileName = UPDATED_IMAGE_STORAGE_PATH;
QFileInfo info(myFileName);
/*find last date modified*/
timeTypeFunction.dateTimeMod1 = info.lastModified();
timeTypeFunction.dateTimeMod2 = info.lastModified();
qDebug()<< "dateTimeMod1: " << timeTypeFunction.dateTimeMod1.toString() << endl << "dateTimeMod2: "<< timeTypeFunction.dateTimeMod2.toString();
return(timeTypeFunction);
}
QDateTime MainWindow::findTimeModified()
{
QString myFileName = UPDATED_IMAGE_STORAGE_PATH;
QFileInfo info(myFileName);
QDateTime dateTimeMod2 = info.lastModified();
qDebug()<< "dateTimeMod2: "<< dateTimeMod2.toString();
return(dateTimeMod2);
}
void MainWindow::compareTimeMods(tTimeMods timeTypeFunction, QDateTime dateTimeMod2)
{
if(dateTimeMod2 >= timeTypeFunction.dateTimeMod1)
{
timeTypeFunction.dateTimeMod1 = dateTimeMod2;
QString pathString = appendWithImageName(timeTypeFunction);
shiftToRepository(pathString);
}
}
QString MainWindow::appendWithImageName(tTimeMods timeTypeFunction)
{
/*appending just the timeMod with the path & image name*/
QString path = QString(UPDATED_IMAGE_BACKUP_PATH).arg(timeTypeFunction.dateTimeMod1.toString());
qDebug()<< "path: " << path;
return path;
}
void MainWindow::shiftToRepository(QString pathString)
{
updatedImgToRepository(pathString);
}
void MainWindow::updatedImgToRepository(QString pathString)
{
pathString.replace(":","-");
pathString.replace(1,1,":");
qDebug()<<"pathString now: "<<pathString;
/*convert QString into char* */
QByteArray pathByteArray = pathString.toLocal8Bit();
const char *path = pathByteArray.data();
IplImage *InputImg = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
InputImg = cvLoadImage(UPDATED_IMAGE_STORAGE_PATH ,CV_LOAD_IMAGE_UNCHANGED);
/*save the image*/
cvSaveImage(path,InputImg);
cvReleaseImage(&InputImg);
}
I'm not familiar with OpenCV, but it seems that these two lines cause you memory leak:
IplImage *InputImg = cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
InputImg = cvLoadImage(UPDATED_IMAGE_STORAGE_PATH ,CV_LOAD_IMAGE_UNCHANGED);
In the first line you are creating an object, but in the second you are assigning another object to the pointer without releasing the previous one, so the previous one gets leaked.
Is creating an image even needed, while you are going to load it?
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.
I want to download the url entered in the line edit widget.
I am not able to get it working , can some one please give me a short code snippet which can put the values of the file to a QString ?
void imdb::on_imdbGetButton_clicked()
{
Qstring link1 = ui->lineEdit2->text();
// QString link1 is the url to be downloaded.
}
I have added , the required header files..
Thanks..
I guess you're trying to download a file via http. Here's what you could do:
In you *.pro file add QT += network
Create an instance of QNetworkAccessManager class;
Supply your file URL to via QNetworkRequest object: manager->get(QNetworkRequest("file_url"));
Connect to the finished signal of the QNetworkAccessManager
In the finished signal handler read the content of the QNetworkReply and save it to the local file.
Below is a small example. Download will start in the button click of the MainForm class:
mainwindow.h:
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QDebug>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFile>
#include <QFileInfo>
#include <QPushButton>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QNetworkAccessManager* _manager;
private slots:
void on_pushButton_clicked();
void downloadFinished(QNetworkReply *reply);
};
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPushButton* button = new QPushButton("Download", this);
button->setGeometry(20, 20, 80, 30);
connect(button, SIGNAL(clicked()), SLOT(on_pushButton_clicked()));
_manager = new QNetworkAccessManager(this);
connect(_manager, SIGNAL(finished(QNetworkReply*)), SLOT(downloadFinished(QNetworkReply*)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QUrl url("http://pics.mtii.com/ClassPictures2011/MIA/E110227-PMIA3-JEAN/thumbnails/P2270448%20copy.jpg");
_manager->get(QNetworkRequest(url));
}
void MainWindow::downloadFinished(QNetworkReply *reply)
{
QUrl url = reply->url();
if (reply->error())
{
qDebug() << "Download of " << url.toEncoded().constData()
<< " failed: " << reply->errorString();
}
else
{
QString path = url.path();
QString fileName = QFileInfo(path).fileName();
if (fileName.isEmpty()) fileName = "download";
QFile file(fileName);
if (file.open(QIODevice::WriteOnly))
{
file.write(reply->readAll());
file.close();
}
qDebug() << "Download of " << url.toEncoded().constData()
<< " succeded saved to: " << fileName;
}
}
hope this helps, regards