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?
Related
I'm trying to use GLEW with QT in a QOpenGLWidget in Visual Studio.
Some details:
Visual Studio 2013
Glew 2.0.0 x64
QT 5.6.2 x64
I keep getting "Missing GL version" error when calling glewInit(). I've searched online a lot, and this problem seems to sometimes be caused by how the format is set (QSurfaceFormat), or how the functions create()/ makeCurrent() / doneCurrent() are used. But I can't seem to find a working solution. I'm still a bit confused about the whole QOpenGLContext thing also.
I manage to get the QOpenGLWidget work without GLEW, and using "old" gl functions (glBegin(), glEnd(), etc...). And I also get GLEW to work with GLFW3.
Is there something I seem to misunderstand in the code below?
My subclass of QOpenGLWidget
MyGLWidget.h
#pragma once
#include <QWidget>
#include "GL\glew.h"
#include <QOpenGLWidget>
#include <gl/GLU.h>
#include <gl/GL.h>
#include <iostream>
#include "qopenglcontext.h"
#include "loadShader.h"
class MyGLWidget : public QOpenGLWidget
{
public:
MyGLWidget(QWidget *parent = 0);
~MyGLWidget();
public:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
};
MyGLWidget.cpp
#include "MyGLWidget.h"
MyGLWidget::MyGLWidget(QWidget *parent)
: QOpenGLWidget(parent)
{
QSurfaceFormat glformat;
glformat.setVersion(3, 2);
glformat.setOption(QSurfaceFormat::DeprecatedFunctions);
glformat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
glformat.setProfile(QSurfaceFormat::CompatibilityProfile);
QSurfaceFormat::setDefaultFormat(glformat);
this->setFormat(glformat);
create();
makeCurrent();
}
MyGLWidget::~MyGLWidget(){}
void MyGLWidget::initializeGL()
{
glewExperimental = TRUE;
GLenum err = glewInit();
if (GLEW_OK != err){
std::cout << "[Error] GLEW failed to initialize. " << (const char*)glewGetErrorString(err);
}
doneCurrent();
GLuint TextShader_ID = LoadShaders("Shaders/TextVertShader.vert", "Shaders/TextFragShader.frag");
}
void MyGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void MyGLWidget::resizeGL(int w, int h)
{
//...
}
main.cpp
#include "OGLQT_test2.h"
#include <QtWidgets/QApplication>
#include "GL\glew.h"
#include <QOpenGLFunctions>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
OGLQT_test2 w;
w.show();
return a.exec();
}
OGLQT_test2.h
#pragma once
#include "GL\glew.h"
#include <QtWidgets/QMainWindow>
#include "ui_OGLQT_test2.h"
#include "qopenglcontext.h"
class OGLQT_test2 : public QMainWindow
{
Q_OBJECT
public:
OGLQT_test2(QWidget *parent = Q_NULLPTR);
private:
Ui::OGLQT_test2Class ui;
};
OGLQT_test2.cpp
#include "OGLQT_test2.h"
#include "MyGLWidget.h"
OGLQT_test2::OGLQT_test2(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
MyGLWidget* glwidget = new MyGLWidget(this);
glwidget->setFixedHeight(400);
glwidget->setFixedWidth(500);
glwidget->move(50, 50);
glwidget->initializeGL();
glwidget->resizeGL(400,500);
glwidget->paintGL();
}
It seems that you cannot do this:
glformat.setVersion(x, y);
with GLEW. It works with QOpenGLFunctions, but apparently, it doesn't work with GLEW. You may not be able to do this, either:
glformat.setOption(QSurfaceFormat::DeprecatedFunctions);
glformat.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
glformat.setProfile(QSurfaceFormat::CompatibilityProfile);
Try removing the format.
Also, I think you're doing a little bit of a mess here:
glwidget->initializeGL();
glwidget->resizeGL(400,500);
glwidget->paintGL();
There is a simple way to do this, just do:
glwidget->resize(400,500);
glwidget->show();
resizeGL is an event called by resize. That goes the same for initializeGL() and paintGL() being called by show.
Another one is:
GLenum err = glewInit();
if (GLEW_OK != err){
std::cout << "[Error] GLEW failed to initialize. " << (const char*)glewGetErrorString(err);
}
doneCurrent();
Now why would you call doneCurrent here?
i am trying to take a feedback data which is published from arduino and subscribed to my GUI created in QT.
Now i have main.cpp and mainwindow.cpp.
main.cpp
#include <QtGui>
#include <ros/ros.h>
#include <QApplication>
#include "../include/abc/main_window.hpp"
#include "std_msgs/String.h"
#include <std_msgs/UInt16.h>
#include <QMainWindow>
#include <std_msgs/Float32.h>
void chatterCallback(const std_msgs::UInt16 &fb_msg){
ROS_INFO("Feedback: [%f]", fb_msg.data);
ui.label_6->setText(QString("%1").arg(fb_msg.data));
}
int main(int argc, char **argv) {
ros::init(argc, argv, "talker");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("feedback",1000, chatterCallback);
ros::spinOnce();
QApplication app(argc, argv);
abc::MainWindow w(argc,argv);
w.show();
w.setWindowTitle("GUI for Controlling Servo Motor");
app.connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()));
int result = app.exec();
return result;}
mainwindow.cpp
namespace abc {
using namespace Qt;
QSerialPort *serial;
MainWindow::MainWindow(int argc, char** argv, QWidget *parent)
: QMainWindow(parent)
, qnode(argc,argv)
{
ui.setupUi(this);
}
MainWindow::~MainWindow() {}
void MainWindow::on_horizontalSlider_valueChanged(int value)
{
ui.label_5->setText(QString("%1").arg(value));
msg.data = ui.label_5->text().toUInt();
ROS_INFO("%d", msg.data);
chatter_pub.publish(msg);
ros::spinOnce();
}
main_window.hpp
#ifndef abc_MAIN_WINDOW_H
#define abc_MAIN_WINDOW_H
#include <QtGui/QMainWindow>
#include "ui_main_window.h"
#include "qnode.hpp"
#include <QtSerialPort/QSerialPort>
#include <ros/ros.h>
#include "std_msgs/UInt16.h"
namespace abc {
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(int argc, char** argv, QWidget *parent = 0);
~MainWindow();
public Q_SLOTS:
private:
Ui::MainWindowDesign ui;
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise <std_msgs::UInt16> ("chatter", 1000);
QSerialPort *arduino;
QNode qnode;
};
} // namespace abc
#endif // abc_MAIN_WINDOW_H
Now when i run this code, it shows me that UI is not declared in main.cpp.
I wanted to display the data from feedback to label_6 (TextBox). The data is only available in main.cpp, any suggestions are highly appreciable.
Thanks in advance.
You will have to pass the fb_msg.data as an argument to the MainWindow constructor. Then you can set the UI element in the MainWindow thread.
Alternatively once you create the MainWindow instance in your main, you can emit a signal which you catch and process in the MainWindow thread.
You cannot modify the UI elements from a different thread.
i’m developing a clock application and I need to do it using Q_PROPERTY. The idea is to make all the clock control logic using C++ and deploy it in a QML GUI.
I got this working on a windows machine but when I run it on a linux distro in a development board I get sometimes undefined text (which are the exposed properties from C++).
The header file is:
#ifndef QCPPCLOCK_H
#define QCPPCLOCK_H
#include <QObject>
#include <QDebug>
#include <QString>
#include <QTime>
#ifdef __linux__
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#endif
class QcppClock : public QObject
{
Q_OBJECT
Q_PROPERTY(QString hours READ hours WRITE setHours NOTIFY hoursChanged)
Q_PROPERTY(QString minutes READ minutes WRITE setMinutes NOTIFY minutesChanged)
private:
QString actualHours;
QString actualMinutes;
QObject* rootObject;
QTime actualTime;
qint8 alarmHour;
qint8 alarmMinutes;
QString timeFormat;
bool alarmSet;
#ifdef __linux__
struct tm* ptm;
struct timeval tv;
#endif
public:
explicit QcppClock(QObject *parent = 0);
QString hours();
void setHours(QString);
QString minutes();
void setMinutes(QString);
public slots:
void qcppClock_vUpdateTextTime_slot(void);
signals:
void qcppClock_vTriggerAlarm_signal(void);
void hoursChanged(void);
void minutesChanged(void);
};
#endif // QCPPCLOCK_H
The .cpp file:
#include "qcppclock.h"
#include <QTimer>
#include <QtCore/qmath.h>
QcppClock::QcppClock(QObject *parent) :
QObject(parent)
{
QTimer* timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(qcppClock_vUpdateTextTime_slot()));
rootObject = parent;
actualTime = QTime::currentTime();
/* Initialize the format to 24 hours */
timeFormat = "24hours";
timer->start(1000);
#ifdef __linux__
gettimeofday (&tv, NULL);
ptm = localtime (&tv.tv_sec);
int hour = ptm->tm_hour;
//setHours(hour);
//actualHours = QString::number(hour);
int minutes = ptm->tm_min;
//setMinutes(minutes);
//actualMinutes = QString::number(minutes);
int seconds = ptm->tm_sec;
(void)actualTime.setHMS(hour , minutes, seconds);
#endif
}
QString QcppClock::hours()
{
return actualHours;
}
void QcppClock::setHours(QString newHours)
{
actualHours = newHours;
#ifdef __linux__
tv.tv_sec += 3600 * actualHours.toInt();
settimeofday(&tv, NULL);
#else
(void)actualTime.setHMS(actualHours.toInt() , actualMinutes.toInt(), actualTime.second());
#endif
emit hoursChanged();
}
QString QcppClock::minutes()
{
return actualMinutes;
}
void QcppClock::setMinutes(QString newMinutes)
{
actualMinutes = newMinutes;
#ifdef __linux__
tv.tv_sec += 60 * actualMinutes.toInt();
settimeofday(&tv, NULL);
#else
(void)actualTime.setHMS(actualHours.toInt() , actualMinutes.toInt(), actualTime.second());
#endif
emit minutesChanged();
}
void QcppClock::qcppClock_vUpdateTextTime_slot(void)
{
actualTime = actualTime.addSecs(1);
actualMinutes = QString::number(actualTime.minute());
emit minutesChanged();
actualHours = QString::number(actualTime.hour());
emit hoursChanged();
QString::number(actualTime.minute());
}
The main file which instantiates the clockctrl object is:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "qcpp_Clock/qcppclock.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QcppClock qcpp_Clock;
QQmlContext* context = engine.rootContext();
context->setContextProperty("clockCtrl", &qcpp_Clock);
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
And the QML file using the exposed properties is:
import QtQuick 2.2
import QtQuick.Window 2.1
Window {
visible: true
width: 800
height: 480
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
Text {
property string prHours: clockCtrl.hours
property string prMinutes: clockCtrl.minutes
text: {
console.log(clockCtrl, clockCtrl.hours, clockCtrl.minutes);
return (prHours + " : " + prMinutes)
}
anchors.centerIn: parent
}
}
As you can see it’s a short and easy code, the problem is in QML when I try to make reference to the C++ exposed properties, i added a couple of consoles in order to see the result in the log and It works like a charm in windows, I never get these “undefined text” but in the development board with linux distro I get sometimes:
qml: QcppClock(0×7e8eeca8) 1 49
qml: QcppClock(0×7e8eeca8) undefined undefined
qml: QcppClock(0×7e8eeca8) 1 49
The first debug is the address of the c++ exposed object in C++, then, the Q_PROPERTY “hour” and the Q_PROPERTY “minutes”.
Thank you in advance.
Ramsés
I want to implement simple commands like a qDebug() when I click on a sub menu in the mainwindow. I was referring to sample program given along with the Qt 5 IDE (...\Qt\Qt5.2.0\5.2.0\msvc2010\examples\widgets\mainwindows\menus), and using it, I managed to construct the code. I do not receive any compile time or run time errors.
I created the mainwindow.ui using the design mode. It has an object of the QAction class called actionInterval.
But when I click on it, nothing happens, I am not able to implement the command in void interval(). I guess I am not connecting properly. What am I missing here? Please advise.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
void createActions();
private slots:
void interval();
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
createActions();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::createActions()
{
ui->actionInterval = new QAction(tr("&Interval"), this);
ui->actionInterval->setStatusTip(tr("Set the interval for capturing delta & reference images"));
connect(ui->actionInterval, SIGNAL(triggered()), this, SLOT(interval()));
}
void MainWindow::interval()
{
qDebug()<<"inside interval qdialog";
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
void MainWindow::createActions()
{
ui->actionInterval->setStatusTip(tr("Set the interval for capturing delta & reference images"));
connect(ui->actionInterval, SIGNAL(triggered()), this, SLOT(interval()));
}
You shouldn't need that ui->actionInterval = new QAction(tr("&Interval"), this); line, the ui->setupUi() handles that for you, so it's potentially causing an incorrect reference so when you do click on it it's not firing correctly.
I derived a class from QTextEdit and use it as a "logbook". I equipped it with a slot to receive log-messages.
class CLogbook : public QTextEdit
{
Q_OBJECT;
public:
void log(QString msg) {append(msg)};
public slots:
void recvLogSignal(const QString message)
{
append("hallo");
std::cout << "signal received.\n";
log(message);
}
};
another class then emits a signal like this:
// in the header
signals:
void logMessage(const QString);
// in the implementation
emit logMessage("qt is cute");
std::cout << "if you can read this the logMessage was emitted\n";
and also i connect the signal to the slot
connect(tableeditor, SIGNAL(logMessage(const QString)), logbook, SLOT(recvLogSignal(const QString)));
However the message is never shown in the "logbook". What am i missing here?
SOLVED: The connect method was called after emitting the signal :-(
It is hard to see exactly what is wrong with your implementation without a full example. Sometimes signals or slots will fail if an object goes out of scope if it isn't initialized on the heap.
Another way that it could fail is if your QApplication hasn't reached the exec() call.
I haven't experimented with using const in signal and slot calls, and I haven't seen it in any examples before, so that could be causing the problem; but it seems to work fine in the example below.
Working Example With a Derived Class of QTextEdit
Here is a simple example I put together that does some basic logging with a push button and a line edit.
Here is the header:
#ifndef WIDGET_H
#define WIDGET_H
#include <QtGui/QWidget>
//#include <QTextEdit>
#include "clogbook.h"
#include <QLineEdit>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget() {}
public slots:
void on_pushButton();
void on_lineEditReturn();
private:
CLogBook * text_edit_log;
QLineEdit * line_edit;
};
#endif // WIDGET_H
Here is the source:
#include "widget.h"
#include <QBoxLayout>
#include <QPushButton>
#include <QTimer>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QBoxLayout * box_layout = new QBoxLayout(QBoxLayout::TopToBottom);
text_edit_log = new CLogBook;
line_edit = new QLineEdit("Type Here and press Enter.");
QPushButton * push_button = new QPushButton("Click to Add To Log");
text_edit_log->setText("My Log Book");
box_layout->addWidget(text_edit_log);
box_layout->addWidget(line_edit);
box_layout->addWidget(push_button);
this->setLayout(box_layout);
QObject::connect(push_button, SIGNAL(clicked()), this, SLOT(on_pushButton()));
QObject::connect(line_edit, SIGNAL(returnPressed()), this, SLOT(on_lineEditReturn()));
}
void Widget::on_pushButton()
{
// text_edit_log->append("Push Button Logging Test");
text_edit_log->recvLogSignal("Push button test.");
}
void Widget::on_lineEditReturn()
{
// text_edit_log->append(line_edit->text());
text_edit_log->recvLogSignal(QString("LineEdit: ") + line_edit->text() );
line_edit->clear();
}
And here is the main:
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
And here is the CLogBook class:
#ifndef CLOGBOOK_H
#define CLOGBOOK_H
#include <QTextEdit>
#include <iostream>
class CLogBook : public QTextEdit
{
Q_OBJECT
public:
explicit CLogBook(QWidget *parent = 0) : QTextEdit(parent) { }
void log (QString msg) { append(msg); }
public slots:
void recvLogSignal(const QString message)
{
append("hallo");
std::cout << "signal received.\n" << std::endl;
log(message);
}
};
#endif // CLOGBOOK_H