QStandardItem converts unsigned int to int after editing - qt

I create a QTableview with a QStandardItemModel, after editing the QStandardItem
the type changed from unsigned int to int.
This behavior just happen to unsigned int and just while the user is editing it, other datatypes stay.
window.cpp
#include "window.h"
#include "ui_window.h"
#include <QTableView>
#include <QStandardItem>
#include <QDebug>
Window::Window(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Window)
{
ui->setupUi(this);
QTableView *tblview = new QTableView(this);
model = new QStandardItemModel(0,0);
tblview->setModel(model);
QStandardItem *data=new QStandardItem;
data->setEditable(true);
data->setData(QVariant((uint)1), Qt::DisplayRole);
model->setItem(0, 0, data);
tblview->show();
QModelIndex index = model->index( 0, 0, QModelIndex() );
tblview->setGeometry(0,0,200,200);
//result QVariant(uint, 1)
qDebug() << model->data(index);
connect(model, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(dataChanged(QStandardItem*)));
}
Window::~Window()
{
delete ui;
}
void Window::dataChanged(QStandardItem* stditem)
{
//result
//QVariant(int, 3)
//expected result
//QVariant(uint, 3)
qDebug() << model->data(stditem->index());
}
window.h
#ifndef WINDOW_H
#define WINDOW_H
#include <QMainWindow>
#include <QStandardItem>
namespace Ui {
class Window;
}
class Window : public QMainWindow
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
~Window();
private:
Ui::Window *ui;
QStandardItemModel* model;
private slots:
void dataChanged(QStandardItem*);
};
#endif // WINDOW_H

The second qDebug() does not print nothing because you do not define the role. This will work:
qDebug() << stditem->data(Qt::DisplayRole);
Now concerning the conversion from an uint QVariant to an int after the edit. This is natural and can be explained as follows:
First you have a QVariant that is uint
QVariant v = QVariant((uint) 5)); // It is uint now...
After the edit, the model changes its value with the int value that is entered
v = QVariant(10); // Now v is not uint anymore but int
In order to avoid it you should subclass the QStandardItemModel, and reimplement the setData function. There you should explicitly cast the new value to uint.

Related

Can a QListView detect a specific QString and therefore automatically trigger a slot?

I have a specific string on a QLineEdit, this string is passed to a QListView via QPushButton. Those strings are choices of a QComboBox and they are very specific:
1) "[ INFO] Minimum Distance: 5",
2) "[ INFO] Minimum Distance: 10" and
3) "[ INFO] Minimum Distance: 15"
Here a perfectly working minimal verifiable example if you need to test it.
Currently I can successfully change the color of the QGraphicsView but by clicking or double-clicking on the QString entered in the QListView.
The problem: How can I detect the specific QString content inside a QListView in order to change the background color of a QGraphicsView?
What I mean I don't want to click or double-click on the entry of the QListView but I would like the QListView to see that there is a string "[ INFO] Minimum Distance: 5" and therefore change the color of the QGraphicsView automatically without me clicking or double-clicking on the QListView entry.
After I "Go to slot" my choices are the following below:
Below the MVE working code, you can copy /paste on your machine and it will work:
mainwindow.h
#include <QMainWindow>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsTextItem>
#include <QStringListModel>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void changeColorDetection();
void updateListView();
void updateListView(const QString & message);
private slots:
void on_pushButton_clicked();
void on_listView_entered(const QModelIndex &index);
void on_listView_activated(const QModelIndex &index);
private:
Ui::MainWindow *ui;
QGraphicsView *mView;
QGraphicsScene *mScene;
QGraphicsTextItem *mText;
StringList *newString;
QStringListModel *model;
};
#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);
mView = new QGraphicsView();
mScene = new QGraphicsScene();
ui->graphicsView->setScene(mScene);
QFont font;
font.setPixelSize(10);
font.setBold(false);
font.setFamily("Calibri");
mText = new QGraphicsTextItem;
mText->setPos(150,70);
mScene->addText(tr("Boat outside alarm area"))->setDefaultTextColor(Qt::black);
model = new QStringListModel();
ui->listView->setModel(model);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
emptyIndex();
connect(ui->listView, SIGNAL(loggingUpdated()), this, SLOT(updateListView(const QString &)));
connect(ui->graphicsView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(on_listView_activated(const QModelIndex &index)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::updateListView(const QString & message)
{
if(model->insertRow(model->rowCount())) {
QModelIndex index = model->index(model->rowCount() - 1, 0);
model->setData(index, message);
ui->listView->scrollTo(index);
}
}
void MainWindow::on_pushButton_clicked()
{
QString str = ui->lineEdit->text();
model->insertRow(model->rowCount());
QModelIndex index = model->index(model->rowCount()-1);
model->setData(index, str);
ui->listView->scrollToBottom();
}
void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
QString list = ui->comboBox->currentText();
ui->lineEdit->setText(list);
Q_UNUSED(arg1)
}
void MainWindow::on_listView_activated(const QModelIndex &index)
{
QStringList allStrings = model->stringList();
QString last = allStrings.last();
if(last.startsWith("[ INFO] Minimum Distance: 5"))
{
ui->graphicsView->setBackgroundBrush(QColor(Qt::red));
}
else if(last.startsWith("[ INFO] Minimum Distance: 10"))
{
ui->graphicsView->setBackgroundBrush(QColor(Qt::yellow));
}
else if(last.startsWith("[ INFO] Minimum Distance: 15"))
{
ui->graphicsView->setBackgroundBrush(QColor(Qt::green));
}
Q_UNUSED(index)
}
EDIT 2
mainwindow.h
#include <QMainWindow>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsTextItem>
#include <QStringListModel>
#include "listview.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void setGraphicViewColor(QColor c);
private:
Ui::MainWindow *ui;
QGraphicsView *mView;
QGraphicsScene *mScene;
QGraphicsTextItem *mText;
QStringListModel *model;
ListView *myListView;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
mView = new QGraphicsView();
mScene = new QGraphicsScene();
ui->graphicsView->setScene(mScene);
QFont font;
font.setPixelSize(10);
font.setBold(false);
font.setFamily("Calibri");
mText = new QGraphicsTextItem;
mText->setPos(150,70);
mScene->addText(tr("Boat outside alarm area"))->setDefaultTextColor(Qt::black);
model = new QStringListModel();
ui->listView->setModel(model);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
connect(ui->listView, SIGNAL(changeColor(QColor)), this, SLOT(setGraphicViewColor(QColor)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setGraphicViewColor(QColor c)
{
qDebug() << "Update your graphicsView backgroundBrush" << c;
ui->graphicsView->setBackgroundBrush(Qt::green);
}
listview.h
#ifndef LISTVIEW_H
#define LISTVIEW_H
#include <QListView>
#include <QStringListModel>
class ListView : public QListView
{
Q_OBJECT
public:
ListView(QWidget *parent = nullptr);
signals:
void changeColor(QColor c);
protected:
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>()) override;
};
#endif // LISTVIEW_H
listview.cpp
#include "listview.h"
ListView::ListView(QWidget *parent)
: QListView(parent)
{}
void ListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
QListView::dataChanged(topLeft, bottomRight, roles);
/**
* Assuming that you have just one item changed
* So topLeft == bottomRight
*/
if (topLeft.row() == model()->rowCount()-1){
QString last = topLeft.data().toString();
if(last.startsWith("[ INFO] Minimum Distance: 5")) {
emit changeColor(Qt::red);
} else if(last.startsWith("[ INFO] Minimum Distance: 10")) {
emit changeColor(Qt::yellow);
} else if(last.startsWith("[ INFO] Minimum Distance: 15")) {
emit changeColor(Qt::green);
}
}
}
Below the error and a screenshot of the ui that does not detect the change event:
The output of the .ui:
What I have done so far:
I have been doinf a lot of research about this problem and came across this source which was useful but could not solve the problem, but in addition it seems to use a QModelIndex and I am not sure this is exactly what I need for this small project.
Also I read this source which was useful to establish and capture the specific and unique string but in terms of changing colors I could not solve that.
Thank you very much for pointing in the right direction for solving this issue.
If I well understand, you want to change the backgroundBrush of your graphicsView if the last item of your QStringListModel starts with your specific strings.
To detect this, you can subclass QListView:
listview.h:
#ifndef LISTVIEW_H
#define LISTVIEW_H
#include <QListView>
#include <QStringListModel>
class ListView : public QListView
{
Q_OBJECT
public:
ListView(QWidget *parent = nullptr);
signals:
void changeColor(QColor c);
protected:
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>()) override;
};
#endif // LISTVIEW_H
listview.cpp:
#include "listview.h"
ListView::ListView(QWidget *parent)
: QListView(parent)
{
}
void ListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
QListView::dataChanged(topLeft, bottomRight, roles);
/**
* Assuming that you have just one item changed
* So topLeft == bottomRight
*/
if (topLeft.row() == model()->rowCount()-1){
QString last = topLeft.data().toString();
if(last.startsWith("[ INFO] Minimum Distance: 5")) {
emit changeColor(Qt::red);
} else if(last.startsWith("[ INFO] Minimum Distance: 10")) {
emit changeColor(Qt::yellow);
} else if(last.startsWith("[ INFO] Minimum Distance: 15")) {
emit changeColor(Qt::green);
}
}
}
Now you have all what you need, but you need to add a slot to connect the signal of your custom ListView with your QGraphicsView::brush
// Add this in your mainwindows.h
public slots:
void setGraphicViewColor(QColor c);
// This in the ctor of your MainWindow:
connect(ui->listView, SIGNAL(changeColor(QColor)), this, SLOT(setGraphicViewColor(QColor)));
// And the implementation of your custom slot in mainwindows.cpp
void MainWindow::setGraphicViewColor(QColor c)
{
qDebug() << "Update your graphicsView backgroundBrush" << c;
//ui->graphicsView->setBackgroundBrush(c);
}

Accessing a delegate's input value from the model

I'm using a custom QTableView with a custom QAbstractTableModel and a QItemDelegate. I'd need to access the contents of the delegate's editor while the user is editing it, and after several attempts, I couldn't find anything satisfying.
Indeed, I've tried several things.
First: trying to access the delegate's current input (created through createEditor) through a property defined in QItemDelegate but... it seems that none exists. That's why I tried to add a QWidget* editor property and setting it in the createEditor.
Unfortunately, QItemDelegate's createEditor is supposed to be const, which makes me unable to set my property there (and since I don't control what calls createEditor, I can't do it before or after).
I don't really know what to do here. Actually, I also needed to know when the user started (or stopped) editing the cell content, which I eventually achieved by creating two const signals (editingStarted and editingStopped). I could probably create a const editorOpened(QWidget*) signal but it just feels bad and ugly...
I can't believe nothing "official" exists to achieve what I'm trying to do, hence this question. If I have everything wrong from the beginning, I'd be glad to know. If you have any other ideas, please suggest.
EDIT: Here is a minimal working example
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include <QTableView>
#include "mytableview.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
auto tableView = new MyTableView(this);
setCentralWidget(tableView);
}
MainWindow::~MainWindow()
{
}
MyItemDelegate.h
#ifndef MYITEMDELEGATE_H
#define MYITEMDELEGATE_H
#include <QItemDelegate>
#include <QLineEdit>
#include <QStandardItemModel>
class MyItemDelegate : public QItemDelegate
{
Q_OBJECT
public:
MyItemDelegate(QObject* parent);
virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;
virtual void onCloseEditor();
virtual ~MyItemDelegate() = default;
signals:
// Const signals trick
void editingStarted() const;
void editingFinished() const;
void editorOpened(const QWidget*) const;
};
#endif // MYITEMDELEGATE_H
MyItemDelegate.cpp
#include "myitemdelegate.h"
MyItemDelegate::MyItemDelegate(QObject* parent) : QItemDelegate(parent)
{
connect(this, &QItemDelegate::closeEditor, this, &MyItemDelegate::onCloseEditor);
}
QWidget* MyItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
auto lineEdit = new QLineEdit(parent);
emit editingStarted();
emit editorOpened(lineEdit);
return lineEdit;
}
void MyItemDelegate::onCloseEditor()
{
emit editingFinished();
}
MyTableView.h
#ifndef MYTABLEVIEW_H
#define MYTABLEVIEW_H
#include <QTableView>
#include <QDebug>
#include "myitemdelegate.h"
class MyTableView : public QTableView
{
Q_OBJECT
public:
explicit MyTableView(QWidget *parent = nullptr);
signals:
public slots:
};
#endif // MYTABLEVIEW_H
MyTableView.cpp
#include "mytableview.h"
MyTableView::MyTableView(QWidget *parent) : QTableView(parent)
{
MyItemDelegate* delegate = new MyItemDelegate(this);
QStandardItemModel* model = new QStandardItemModel(this);
setItemDelegate(delegate);
setModel(model);
QList<QList<QStandardItem*>> items;
for(int i = 0; i < 10; i++)
{
items << QList<QStandardItem*>();
for (int j = 'A'; j < 'E'; j++)
items[i] << new QStandardItem(QString("%1,%2").arg(i).arg(static_cast<char>(j)));
}
for (const auto& row : items)
model->appendRow(row);
connect(delegate, &MyItemDelegate::editingStarted, []() {
qDebug() << "Editing started";
});
connect(delegate, &MyItemDelegate::editingFinished, []() {
qDebug() << "Editing finished";
});
connect(delegate, &MyItemDelegate::editorOpened, [](const QWidget* editor) {
auto lineEdit = qobject_cast<const QLineEdit*>(editor);
connect(lineEdit, &QLineEdit::textChanged, [](const QString& text) {
qDebug() << text;
});
});
}
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 following solution maybe fits your needs. I just defined a new signal inside the delegate and connected to it inside the class owning the delegate.
MyItemDelegate.h
#ifndef MYITEMDELEGATE_H
#define MYITEMDELEGATE_H
#include <QStyledItemDelegate>
class MyItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
MyItemDelegate(QObject* parent);
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;
virtual ~MyItemDelegate() = default;
signals:
void valueChanged(const QString&);
};
#endif // MYITEMDELEGATE_H
MyItemDelegate.cpp
#include "myitemdelegate.h"
#include <QLineEdit>
MyItemDelegate::MyItemDelegate(QObject* parent) : QStyledItemDelegate(parent)
{
}
QWidget* MyItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
auto lineEdit = new QLineEdit(parent);
connect(lineEdit, &QLineEdit::textChanged, this, &MyItemDelegate::valueChanged);
return lineEdit;
}
MyTableView.cpp
#include "mytableview.h"
#include <QStandardItemModel>
MyTableView::MyTableView(QWidget *parent) : QTableView(parent)
{
MyItemDelegate* delegate = new MyItemDelegate(this);
QStandardItemModel* model = new QStandardItemModel(this);
setItemDelegate(delegate);
setModel(model);
QList<QList<QStandardItem*>> items;
for(int i = 0; i < 10; i++)
{
items << QList<QStandardItem*>();
for (int j = 'A'; j < 'E'; j++)
items[i] << new QStandardItem(QString("%1,%2").arg(i).arg(static_cast<char>(j)));
}
for (const auto& row : items)
model->appendRow(row);
connect(delegate, &MyItemDelegate::valueChanged, [](auto v) { qDebug() << v; });
}

Why QCompleter works differently with delegates?

I am trying to implement auto-completion for QLineEdit.
Here see my code:
#ifndef COMPLETER_H
#define COMPLETER_H
#include <QCompleter>
#include <QString>
#include <QStringList>
#include <QLineEdit>
class Completer:public QCompleter
{
Q_OBJECT
public:
explicit Completer(QStringList stringList, QObject *parent=0);
virtual QString pathFromIndex(const QModelIndex &index)const;
virtual QStringList splitPath(const QString&)const;
public slots:
void onLineEditTextChanged() const;
private:
mutable int cursorPos_;
};
class ExpressionLineEdit: public QLineEdit
{
Q_OBJECT
public:
explicit ExpressionLineEdit(QWidget *parent=0);
private:
QStringList stringList;
Completer *completer_;
};
#endif // COMPLETER_H
#include <completer.h>
#include <QDebug>
Completer::Completer(QStringList stringList, QObject *parent)
: QCompleter(stringList,parent)
, cursorPos_(-1)
{
}
ExpressionLineEdit::ExpressionLineEdit(QWidget* parent)
: QLineEdit(parent)
{
stringList << "minRoute" << "minPitch" << "minSpacing";
completer_ = new Completer(stringList, this);
setCompleter(completer_);
QObject::connect(this, SIGNAL(textChanged(const QString&)),
completer_, SLOT(onLineEditTextChanged()));
QObject::connect(this, SIGNAL(cursorPositionChanged(int, int)),
completer_, SLOT(onLineEditTextChanged()));
}
QString Completer::pathFromIndex(const QModelIndex &index) const
{
QString newStr = index.data(Qt::EditRole).toString();
ExpressionLineEdit *lineEdit = qobject_cast<ExpressionLineEdit*>(parent());
QString str = lineEdit->text();
int prevSpacePos = str.mid(0, lineEdit->cursorPosition()).lastIndexOf(' ');
int curPos = lineEdit->cursorPosition();
int nextSpacePos = str.indexOf(' ', curPos);
if (nextSpacePos == -1) {
nextSpacePos = str.size();
}
QString part1 = str.mid(0, prevSpacePos + 1);
QString pre = str.mid(prevSpacePos + 1, curPos - prevSpacePos - 1);
QString post = str.mid(curPos, nextSpacePos - curPos);
QString part2 = str.mid(nextSpacePos);
onLineEditTextChanged();
cursorPos_ = curPos + newStr.size() - pre.size();
return part1 + newStr + part2;
}
void Completer::onLineEditTextChanged() const
{
qDebug() << "Completer::onLineEditTextChanged()" << cursorPos_;
if (cursorPos_ != -1) {
ExpressionLineEdit *lineEdit = qobject_cast<ExpressionLineEdit*>(parent());
lineEdit->setCursorPosition(cursorPos_);
cursorPos_ = -1;
}
}
QStringList Completer::splitPath(const QString &path) const
{
cursorPos_ = -1;
ExpressionLineEdit *lineEdit = qobject_cast<ExpressionLineEdit*>(parent());
QString text = lineEdit->text();
QStringList stringList;
QString str;
int index = text.mid(0,lineEdit->cursorPosition()).lastIndexOf(' ');
str = text.mid(index, lineEdit->cursorPosition()-index);
str.trimmed();
str.replace(" ", "");
stringList << str;
onLineEditTextChanged();
return stringList;
}
#include <completer.h>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ExpressionLineEdit le;
le.show();
return a.exec();
}
For this code ExpressionLineEdit and Completer work properly (as expected).
But when I try to set the to QTreeView and QSyledItemDelegate, the the behavior is changed.
I tried to reimplement the eventFilter function of QSyledItemDelegate, but it does not word.
I tried to set ExpressionLineEdit to other QWidget and set the QWidget to QTreeView (for QSyledItemDelegate not to work with ExpressionLineEdit directly), but again it did not help.
Here is the code with QTreeView and QSyledItemDelegate.
#include <QTreeView>
#include <QVBoxLayout>
#include <QStandardItemModel>
#include <QStyledItemDelegate>
#include <Completer.h>
class QEvent;
class Delegate:public QStyledItemDelegate
{
public:
Delegate(QObject* parent = 0)
:QStyledItemDelegate(parent){}
bool eventFilter(QObject* editor,QEvent* event){return false;}
virtual bool editorEvent ( QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex& index){return false;}
QWidget* createEditor(QWidget* parent,const QStyleOptionViewItem &option,const QModelindex &index) const
{
if(index.column() != 1) return 0;
QWidget* w = new QWidget(parent);
ExpressionLineEdit *le = new ExpressionLineEdit(w);
QVBoxLayout* lay = new QVBoxLayout(w);
lay->setContentsMargins(0, 0, 0, 0);
lay->addWidget(le);
w->setLayout(lay);
return w;
}
};
class Tree:public QTreeView
{
public:
Tree(QWidget* parent = 0)
:QTreeView(parent)
{
QStandardItemModel *model = new QStandardItemModel(this);
model->setRowCount(1);
model->setColumnCount(2);
QStandardItem *item = new QStandardItem("Item");
model->setItem(0,0,item);
setModel(model);
Delegate *d = new Delegate(this);
setItemDelegate(d);
}
void keyPressEvent ( QKeyEvent * event ){}
};
#include <QApplication>
#include <Completer.h>
#include <Tree.h>
int main(int argc, char ** argv)
{
QApplication app(argc,argv);
Tree t;
t.show();
return app.exec();
}
Please help to understand why same code works differently for this 2 cases.
Please help to fix the behavior of Completer.

Windows Task Manager shows process memory keeps growing

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?

How to make a QSlider change with double values

My problem is that I just can't seem to make my QSlider work with double values instead of integer, because I need to make it return double values to a QLineEdit and also set it's own value when I put some value in the edit.
When I was a Qt beginner I started with this tutorial. It is a little bit old (it refers to Qt4.1), but it was good enough to get me started!
I have put together a simple example application that can show you where to start... Maybe you can find it helpful!
#include <QApplication>
#include <QtGui>
#include <QVBoxLayout>
#include <QSlider>
#include <QLabel>
class DoubleSlider : public QSlider {
Q_OBJECT
public:
DoubleSlider(QWidget *parent = 0) : QSlider(parent) {
connect(this, SIGNAL(valueChanged(int)),
this, SLOT(notifyValueChanged(int)));
}
signals:
void doubleValueChanged(double value);
public slots:
void notifyValueChanged(int value) {
double doubleValue = value / 10.0;
emit doubleValueChanged(doubleValue);
}
};
class Test : public QWidget {
Q_OBJECT
public:
Test(QWidget *parent = 0) : QWidget(parent),
m_slider(new DoubleSlider()),
m_label(new QLabel())
{
m_slider->setOrientation(Qt::Horizontal);
m_slider->setRange(0, 100);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(m_slider);
layout->addWidget(m_label);
connect(m_slider, SIGNAL(doubleValueChanged(double)),
this, SLOT(updateLabelValue(double)));
updateLabelValue(m_slider->value());
}
public slots:
void updateLabelValue(double value) {
m_label->setText(QString::number(value, 'f', 2));
}
private:
QSlider *m_slider;
QLabel *m_label;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Test *wid = new Test();
wid->show();
return a.exec();
}
#include "main.moc"
You can simply divide slider value on some constant. For example:
const int dpi = 10; // Any constant 10^n
int slideVal = 57; // Integer value from slider
double realVal = double( slideVal / dpi ); // float value

Resources