QDataStream serialize pointer - c++

I am implementing a little interface with Qt. In the step I am currently working on, I have Scores (custom class) I can move on Docks (again, custom class) that can hold only one Score.
I inspired myself (a lot) with this example: Fridge magnets.
In this configuration, the information of the dragged object are brought along thanks to a QByteArray, stocked in the mime data, thanks to serialization by QDataStream.
I would like for a Score, when dropped on an occupied Dock, to make the "residing" Score to go to his original space. I thought I could do that by having an attribute containing the adress of its original Dock, but I can't get this pointer stocked in the datastream.
Here follows part of my code:
/* Part of the definition of my classes */
class Score : public QLabel
{
Q_OBJECT
protected:
QString labelText;
Dock * dock;
QImage * click;
};
class Dock : public QFrame
{
Q_OBJECT
protected:
Score * score;
};
/* And the 4 methods allowing the drag and drop */
void Dock::mousePressEvent(QMouseEvent *event)
{
Score * child = dynamic_cast<Score *>(childAt(event->pos()));
if (!child)
return;
QPoint hotSpot = event->pos() - child->pos();
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << child->getLabelText() << child->getClick() << QPoint(hotSpot);
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-score", itemData);
mimeData->setText(child->getLabelText());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(QPixmap::fromImage(*child->getClick()));
drag->setHotSpot(hotSpot);
child->hide();
if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
child->close();
else
child->show();
}
void Dock::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-score"))
{
if (children().contains(event->source()))
{
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
event->acceptProposedAction();
}
else
event->ignore();
}
void Dock::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("application/x-score"))
{
if (children().contains(event->source()))
{
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
event->acceptProposedAction();
}
else
event->ignore();
}
void Dock::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasFormat("application/x-score"))
{
const QMimeData *mime = event->mimeData();
QByteArray itemData = mime->data("application/x-score");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);
QString text;
QImage * img;
QPoint offset;
dataStream >> text >> img >> offset;
Score * newScore = new Score(text, this);
newScore->show();
newScore->setAttribute(Qt::WA_DeleteOnClose);
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
}
else
event->acceptProposedAction();
}
else
event->ignore();
static_cast<FrameCC *>(parentWidget())->calcTotal();
}
I couldn't overload the << and the >> operator for QDataStream and Dock * because the only way I found of doing that with a pointer was to stock the actual data. But the problem is I don't want the data, I litteraly just need the pointer!
I you have an idea, even if it means I have to rethink the way of doing this, I would gladly hear it. Thank you!

If I understood right, you'd like to serialize a pointer to a dock? I don't really understand why you are doing this the hard way.
What about this:
make your mime-data simply a pointer to the score like itemData.fromRawData(reinterpret_cast<char*>(&score, sizeof(Score&ast;)));
in the dropEvent()
use event->source() to get the dock's pointer
use another stream and the reverse procedure to extract the pointer from the mimeData, or simply an uber-cast union:
union {char chr[8]; Score &ast;score} scorecast;
memcpy(scorecast.chr, itemData.data(), sizeof(Score&ast;));
, then access your score-pointer via scorecast.score
That would also save you from sending around all the data in the Score-to-drop ...
Just a last thought: QByteArray.data() gives a const char * to the data making up your pointer. What about *reinterpret_cast<Score * *>(imageData.data()) to get your pointer back?
And a second last though came up reading my own QDataStream marshalling code:
QDataStream & operator << (QDataStream & s, const Score * scoreptr)
{
qulonglong ptrval(*reinterpret_cast<qulonglong *>(&scoreptr));
return s << ptrval;
}
QDataStream & operator >> (QDataStream & s, Score *& scoreptr)
{
qulonglong ptrval;
s >> ptrval;
scoreptr = *reinterpret_cast<Score **>(&ptrval);
return s;
}

Related

How to save the image in clipboard in variable and restore it to clipboard later?

I connect a slot to the dataChanged signal of QClipboard to store the image in the clipboard to a variable mimedata(reference):
void MyWin::clipboardDataChanged()
{
const QMimeData * m=QApplication::clipboard()->mimeData();
mimedata = new QMimeData();
foreach(QString format, m->formats())
{
QByteArray data = m->data(format);
if(format.startsWith("application/x-qt"))
{
int index1 = format.indexOf('"') + 1;
int index2 = format.indexOf('"', index1);
format = format.mid(index1, index2 - index1);
}
mimedata->setData(format, data);
}
}
And restore mimedata to clipboard as follows:
void MyWin::onrestore()
{
QApplication::clipboard()->setMimeData(mimedata);
}
However, the data set to the clipboard seems corrupted. If I paste from the clipboard to Paint, it says "The information on the Clipboard can't be inserted into Paint." I printed the format of the data in the clipboard, i.e., "application/x-qt-image". So I think it is not a format that is supported by other applications. Is this a bug of Qt or the code is flawed?
I think you'd be better save the whole clipboard content, so you can safely restore it when needed, i.e.
void MyWin::clipboardDataChanged()
{
const QMimeData * m = QApplication::clipboard()->mimeData();
mimedata = new QMimeData();
for(auto format : m->formats())
{
mimedata->setData(format, m->data(format));
}
}
Alternatively, convert the application/x-qt-image data into a QImage, then use QMimeData::setImageData to store it:
void MyWin::clipboardDataChanged()
{
const QMimeData * m = QApplication::clipboard()->mimeData();
mimedata = new QMimeData();
for(auto format : m->formats())
{
if(format == "application/x-qt-image")
{
QImage image;
QByteArray data = m->data(format);
QBuffer buffer(&data);
image.load(&buffer, nullptr);
mimedata->setImageData(image);
}
}
}

SQL Parameter count mismatch on QTableView

I have a GUI composed of:
N.1 GraphicsView
N.1 QTableView
N.1 dialog that opens up as needed by the user after doubleclicking on each row of the QTableView
I can capture features on the QGraphicsView with the mouse click. After the feature is drawn I right click and open up a dialog like the one in the figure:
After hitting accept: I register the feature as the row index of the QTableView as shown below:
If I doubleclick on each row I am able to open again the same dialog with the information previously saved. I do that because I may need to change the name of the image and call it differently.
The problem I currently have is that I ma receiving a weird Parameter count mismatch from the compiler and I don't understand why and it should be due to QSQLITE
Below is what I am trying to do along with the most important part of the code:
parameters.h
typedef struct Param
{
int mId;
QString mName;
QByteArray mSave;
} Param;
class Parameters
{
public:
Parameters() = default;
Parameters(Param newdata);
Parameters(int id, const QString &name, const QByteArray &save);
int id() const { return data.mId; }
QString name() const {return data.mName; }
QByteArray save() const {return data.mSave; }
Param getData() const { return data; }
void setData(Param ndat) { data = ndat; }
private:
Param data;
};
parameters.cpp
#include "parameters.h"
Parameters::Parameters(Param newdata) {
data = newdata;
}
Parameters::Parameters(int id, const QString &name,
const QByteArray &save) {
data.mId = id;
data.mSave = save;
data.mName = name;
}
the database is set in the following dataleftcamera.h part:
public:
explicit dataLeftCamera(QObject *parent = nullptr);
bool addItem(Parameters* mParameters);
bool updateItem(int itemId, Parameters* mParameters);
QSqlDatabase getDatabase();
private:
QString mError;
QSqlDatabase mDatabaseLeft;
The table is initiated here on dataleftcamera.cpp and here is where the compiler is giving the Parameter count mismatch error specifically on the function updateItem
#define CREATE_TABLE \
" CREATE TABLE IF NOT EXISTS leftCamTable" \
" (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" \
", name TEXT NOT NULL" \
", save BLOB NOT NULL)"
dataLeftCamera::dataLeftCamera(QObject *parent) : QObject (parent)
{}
bool dataLeftCamera::addItem(Parameters *mParameters)
{
QSqlQuery qry;
qry.prepare("INSERT INTO leftCamTable (name, save)"\
" VALUES (?,?)");
qry.addBindValue(mParameters->name());
qry.addBindValue(mParameters->save());
bool ok = qry.exec();
if(!ok) {
mError = qry.lastError().text();
qDebug() << mError;
}
}
bool dataLeftCamera::updateItem(int itemId, Parameters *mParameters)
{
QSqlQuery qry;
qry.prepare(" UPDATE lefCamTable SET " \
" name = ?," \
" save = ?" \
" WHERE id = ?");
qry.addBindValue(mParameters->name());
qry.addBindValue(mParameters->save());
qry.addBindValue(itemId);
bool ok = qry.exec();
if(!ok) {
mError = qry.lastError().text();
qDebug() << mError;
}
}
On the mainwindow.cpp is the part where I update the item after I doubleclick on the row to change the name of the image and accept again the modification:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mDatabaseLeftCamera = new dataLeftCamera(this);
mModelLeftCamera = nullptr;
mModelLeftCamera = new QSqlTableModel(this);
ui->tableView->setModel(mModelLeftCamera);
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(onTableClick(QModelIndex)));
// temporary folder
temporaryFolder = "/home/name/Desktop/tempDBFolder/tmp.db";
QFile dbRem(temporaryFolder);
dbRem.remove();
mDatabaseLeftCamera->inizializationDatabaseLeftCamera(temporaryFolder);
mDatabaseLeftCamera->configurationDatabaseLeftCamera();
mModelLeftCamera = new QSqlTableModel(this, mDatabaseLeftCamera->getDatabase());
mModelLeftCamera->setTable("leftCamTable");
mModelLeftCamera->select();
ui->tableView->setModel(mModelLeftCamera);
ui->tableView->showColumn(true);
}
// opening the dialog for the first time after capturing the image
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
// operations
Param result = d.getData();
Parameters* param = new Parameters(result);
mDatabaseLeftCamera->addItem(param);
mModelLeftCamera->select();
ui->tableView->show();
}
// This is the doubleclick that re-opens the small dialog to change the name of the feature
void MainWindow::onTableClick(const QModelIndex &index)
{
int row = index.row();
Param currentData;
int ItemId = index.sibling(row, 0).data().toInt();
currentData.mName = index.sibling(row, 1).data().toString();
currentData.mSave = index.sibling(row, 2).data().toByteArray();
QPixmap iconPix;
if(!iconPix.loadFromData(index.sibling(row, 2).data().toByteArray())) {
}
clipSceneDialog d(this);
d.show();
d.setData(currentData);
d.setImage(iconPix.toImage());
if(d.exec() == QDialog::Rejected) {
return;
} else {
//
}
Param result = d.getData();
Parameters* param = new Parameters(result);
mDatabaseLeftCamera->updateItem(ItemId,param);
mModelLeftCamera->select();
ui->tableView->show();
}
For completeness see the error the compiler is giving if that helps:
I am sorry if this is trivial but I checked the updateItem(ItemId,param)
and thanks for shedding light on this.
Try and add some debug printing. Especially for the parameters that you add to the prepared statement. qry.addBindValue converts your value to a QVariant. Based on the documentation QVariants become NULL when they contain no data:
QVariant x(QString());
// x.isNull() == true
In case there is a problem retrieving your parameters, this could explain the violation of the NOT NULL constraints.

How to display graphics objects behind or foreground of text inside QTextEdit in Qt?

I would like to display a rectangle behind a word I selected like Qt Creator does here:
I am experimenting with the example of QSyntaxHighlighter. I am able to change styles based on keyword patterns. I would like to have graphics or widgets for custom autocompletion lists.
For autocompletion follow the Custom Completer Example or the Completer Example.
The code below follows the first one, which I blatantly, unashamedly copied and integrated into the BackgroundHighlighter class and main.cpp.
This answer will contain five files within a project along with a Qt Resource File.
highlighter.h (Highlighter Class for Syntax)
highlighter.cpp
backgroundHighlighter.h (BackgroundHighlighter Class)
backgroundHighlighter.cpp
main.cpp
res.qrc (optional, not needed, you can hardcode your text)
res (directory) (optional)
|- symbols.txt (optional, you can set your own default text)
|- wordlist.txt (optional, copied from example but you could use your own line-delimited word list and set this in main.cpp with a QStringListModel)
Note that the implementation of the Highlighter class for (1) and (2) can be found in the Qt Syntax Highlighter Example. I will leave its implementation as an exercise for the reader.
In calling the BackgroundHighlighter class, one can pass it a file name to load text from a file. (This wasn't in the OP's specification, but was convenient to implement due to the large amount of text I wanted to test.)
Also note that I integrated the Custom Completer Example into the class.
Here's backgroundHighlighter.h (3) (~45 lines, ~60 lines with completer):
#ifndef BACKGROUNDHIGHLIGHTER_H
#define BACKGROUNDHIGHLIGHTER_H
#include <QtWidgets>
#include <QtGui>
// this is the file to your highlighter
#include "myhighlighter.h"
class BackgroundHighlighter : public QTextEdit
{
Q_OBJECT
public:
BackgroundHighlighter(const QString &fileName = QString(), QWidget *parent = nullptr);
void loadFile(const QString &fileName);
void setCompleter(QCompleter *completer);
QCompleter *completer() const;
protected:
void keyPressEvent(QKeyEvent *e) override;
void focusInEvent(QFocusEvent *e) override;
public slots:
void onCursorPositionChanged();
private slots:
void insertCompletion(const QString &completion);
private:
// this is your syntax highlighter
Highlighter *syntaxHighlighter;
// stores the symbol being highlighted
QString highlightSymbol;
// stores the position (front of selection) where the cursor was originally placed
int mainHighlightPosition;
// stores character formats to be used
QTextCharFormat mainFmt; // refers to format block directly under the cursor
QTextCharFormat subsidiaryFmt; // refers to the formatting blocks on matching words
QTextCharFormat defaultFmt; // refers to the default format of the **entire** document which will be used in resetting the format
void setWordFormat(const int &position, const QTextCharFormat &format);
void runHighlight();
void clearHighlights();
void highlightMatchingSymbols(const QString &symbol);
// completer, copied from example
QString textUnderCursor() const;
QCompleter *c;
};
#endif // BACKGROUNDHIGHLIGHTER_H
And here's backgroundHighlighter.cpp (4) (~160 lines, ~250 lines with completer):
#include "backgroundhighlighter.h"
#include <QDebug>
// constructor
BackgroundHighlighter::BackgroundHighlighter(const QString &fileName, QWidget *parent) :
QTextEdit(parent)
{
// I like Monaco
setFont(QFont("Monaco"));
setMinimumSize(QSize(500, 200));
// load initial text from a file OR from a hardcoded default
if (!fileName.isEmpty())
loadFile(fileName);
else
{
QString defaultText = "This is a default text implemented by "
"a stackoverflow user. Please upvote the answer "
"at https://stackoverflow.com/a/53351512/10239789.";
setPlainText(defaultText);
}
// set the highlighter here
QTextDocument *doc = document();
syntaxHighlighter = new Highlighter(doc);
// TODO change brush/colours to match theme
mainFmt.setBackground(Qt::yellow);
subsidiaryFmt.setBackground(Qt::lightGray);
defaultFmt.setBackground(Qt::white);
// connect the signal to our handler
connect(this, &QTextEdit::cursorPositionChanged, this, &BackgroundHighlighter::onCursorPositionChanged);
}
// convenience function for reading a file
void BackgroundHighlighter::loadFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
return;
// the file could be in Plain Text OR Html
setText(file.readAll());
}
void BackgroundHighlighter::setCompleter(QCompleter *completer)
{
if (c)
QObject::disconnect(c, 0, this, 0);
c = completer;
if (!c)
return;
c->setWidget(this);
c->setCompletionMode(QCompleter::PopupCompletion);
c->setCaseSensitivity(Qt::CaseInsensitive);
QObject::connect(c, SIGNAL(activated(QString)),
this, SLOT(insertCompletion(QString)));
}
QCompleter *BackgroundHighlighter::completer() const
{
return c;
}
void BackgroundHighlighter::keyPressEvent(QKeyEvent *e)
{
if (c && c->popup()->isVisible()) {
// The following keys are forwarded by the completer to the widget
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
e->ignore();
return; // let the completer do default behavior
default:
break;
}
}
bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
if (!c || !isShortcut) // do not process the shortcut when we have a completer
QTextEdit::keyPressEvent(e);
const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
if (!c || (ctrlOrShift && e->text().isEmpty()))
return;
static QString eow("~!##$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word
bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
QString completionPrefix = textUnderCursor();
if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
|| eow.contains(e->text().right(1)))) {
c->popup()->hide();
return;
}
if (completionPrefix != c->completionPrefix()) {
c->setCompletionPrefix(completionPrefix);
c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
}
QRect cr = cursorRect();
cr.setWidth(c->popup()->sizeHintForColumn(0)
+ c->popup()->verticalScrollBar()->sizeHint().width());
c->complete(cr); // pop it up!
}
void BackgroundHighlighter::focusInEvent(QFocusEvent *e)
{
if (c)
c->setWidget(this);
QTextEdit::focusInEvent(e);
}
// convenience function for setting a `charFmt` at a `position`
void BackgroundHighlighter::setWordFormat(const int &position, const QTextCharFormat &charFmt)
{
QTextCursor cursor = textCursor();
cursor.setPosition(position);
cursor.select(QTextCursor::WordUnderCursor);
cursor.setCharFormat(charFmt);
}
// this will handle the `QTextEdit::cursorPositionChanged()` signal
void BackgroundHighlighter::onCursorPositionChanged()
{
// if cursor landed on different format, the `currentCharFormat` will be changed
// we need to change it back to white
setCurrentCharFormat(defaultFmt);
// this is the function you're looking for
runHighlight();
}
void BackgroundHighlighter::insertCompletion(const QString &completion)
{
if (c->widget() != this)
return;
QTextCursor tc = textCursor();
int extra = completion.length() - c->completionPrefix().length();
tc.movePosition(QTextCursor::Left);
tc.movePosition(QTextCursor::EndOfWord);
tc.insertText(completion.right(extra));
setTextCursor(tc);
}
QString BackgroundHighlighter::textUnderCursor() const
{
QTextCursor tc = textCursor();
tc.select(QTextCursor::WordUnderCursor);
return tc.selectedText();
}
/**
* BRIEF
* Check if new highlighting is needed
* Clear previous highlights
* Check if the word under the cursor is a symbol (i.e. matches ^[A-Za-z0-9_]+$)
* Highlight all relevant symbols
*/
void BackgroundHighlighter::runHighlight()
{
// retrieve cursor
QTextCursor cursor = textCursor();
// retrieve word under cursor
cursor.select(QTextCursor::WordUnderCursor);
QString wordUnder = cursor.selectedText();
qDebug() << "Word Under Cursor:" << wordUnder;
// get front of cursor, used later for storing in `highlightPositions` or `mainHighlightPosition`
int cursorFront = cursor.selectionStart();
// if the word under cursor is the same, then save time
// by skipping the process
if (wordUnder == highlightSymbol)
{
// switch formats
setWordFormat(mainHighlightPosition, subsidiaryFmt); // change previous main to subsidiary
setWordFormat(cursorFront, mainFmt); // change position under cursor to main
// update main position
mainHighlightPosition = cursorFront;
// jump the gun
return;
}
// clear previous highlights
if (mainHighlightPosition != -1)
clearHighlights();
// check if selected word is a symbol
if (!wordUnder.contains(QRegularExpression("^[A-Za-z0-9_]+$")))
{
qDebug() << wordUnder << "is not a symbol!";
return;
}
// set the highlight symbol
highlightSymbol = wordUnder;
// store the cursor position to check later
mainHighlightPosition = cursorFront;
// highlight all relevant symbols
highlightMatchingSymbols(wordUnder);
qDebug() << "Highlight done\n\n";
}
// clear previously highlights
void BackgroundHighlighter::clearHighlights()
{
QTextCursor cursor = textCursor();
// wipe the ENTIRE document with the default background, this should be REALLY fast
// WARNING: this may have unintended consequences if you have other backgrounds you want to keep
cursor.select(QTextCursor::Document);
cursor.setCharFormat(defaultFmt);
// reset variables
mainHighlightPosition = -1;
highlightSymbol.clear();
}
// highlight all matching symbols
void BackgroundHighlighter::highlightMatchingSymbols(const QString &symbol)
{
// highlight background of congruent symbols
QString docText = toPlainText();
// use a regex with \\b to look for standalone symbols
QRegularExpression regexp("\\b" + symbol + "\\b");
// loop through all matches in the text
int matchPosition = docText.indexOf(regexp);
while (matchPosition != -1)
{
// if the position
setWordFormat(matchPosition, matchPosition == mainHighlightPosition ? mainFmt : subsidiaryFmt);
// find next match
matchPosition = docText.indexOf(regexp, matchPosition + 1);
}
}
Finally, here's main.cpp (5) (~10 lines, ~45 lines with completer)
#include <QApplication>
#include <backgroundhighlighter.h>
QAbstractItemModel *modelFromFile(const QString& fileName, QCompleter *completer)
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly))
return new QStringListModel(completer);
#ifndef QT_NO_CURSOR
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif
QStringList words;
while (!file.atEnd()) {
QByteArray line = file.readLine();
if (!line.isEmpty())
words << line.trimmed();
}
#ifndef QT_NO_CURSOR
QApplication::restoreOverrideCursor();
#endif
return new QStringListModel(words, completer);
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
BackgroundHighlighter bh(":/res/symbols.txt");
QCompleter *completer = new QCompleter();
completer->setModel(modelFromFile(":/res/wordlist.txt", completer));
// use this and comment the above if you don't have or don't want to use wordlist.txt
// QStringListModel *model = new QStringListModel(QStringList() << "aaaaaaa" << "aaaaab" << "aaaabb" << "aaacccc",
completer);
// completer->setModel(model);
completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
completer->setCaseSensitivity(Qt::CaseInsensitive);
completer->setWrapAround(false);
bh.setCompleter(completer);
bh.show();
return a.exec();
}
In res.qrc add a / prefix and add files (res/symbols.txt, res/wordlist.txt) from the res/ subdirectory.
I have tested with a symbols.txt file resembling
symbol1 symbol2 symbol3 symbol4 symbol5
symbol1 symbol2 symbol3 symbol4 symbol5
symbol1 symbol2 symbol3 symbol4 symbol5
// ... ditto 500 lines
It takes about 1 second, which probably isn't ideal (100ms is probably more ideal).
However, you might want to watch over for the line count as it grows. With the same text file at 1000 lines, the program will start to take approx. 3 seconds for highlighting.
Note that... I haven't optimised it entirely. There could possibly be a better implementation which formats only when the symbol scrolls into the user's view. This is just a suggestion. How to implement it I don't know.
Notes
For reference, I've attached symbols.txt and wordlist.txt on github.
If you want to change the background colour of formatting, go to lines 27 to 29 of backgroundhighlighter.cpp. There, you can see that I centralised the formatting.
BackgroundHighlighter::clearHighlights() might clear away any background highlights originally added as it sets the ENTIRE document's character background to the default format. This may be an unintended consequence of the result.

Child items not movable in QGraphicsView when ItemIsMovable flag is set

To resize items in a QGraphicsView, I'm putting child items representing vertices onto the item to be moved (using the parent-child relationship established in the constructor). Those are the four blue circles in the picture below:
But the child vertices are not receiving mouse events. Only the parent item (red square) is getting mouse events.
Here is the definition for Item:
Item::Item(QGraphicsItem * parent) :
QGraphicsItem(parent)
{
setFlag(ItemIsMovable);
setFlag(ItemIsSelectable);
setFlag(ItemSendsGeometryChanges);
setCacheMode(DeviceCoordinateCache);
}
void Item::paint(
QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->fillRect(option->rect,Qt::red);
}
QVariant Item::itemChange(GraphicsItemChange change, const QVariant & value)
{
switch(change)
{
case QGraphicsItem::ItemSelectedHasChanged:
qWarning() << "item: " + value.toString();
updateVertices(value.toBool());
break;
default:
break;
}
return QGraphicsItem::itemChange(change, value);
}
void Item::updateVertices(bool visible) {
if(visible) {
if(vertices.length() == 0) {
for(int i = 0; i < 4; i++)
vertices.append(new Vertice(this));
} else
for(int i = 0; i < 4; i++)
vertices[i]->setVisible(true);
QRectF rect = boundingRect();
vertices[0]->setPos(rect.topLeft());
vertices[1]->setPos(rect.topRight());
vertices[2]->setPos(rect.bottomLeft());
vertices[3]->setPos(rect.bottomRight());
} else {
for(int i = 0; i < 4; i++) {
p_vertices[i]->setVisible(false);
}
}
}
While here is the definition for Vertice:
Vertice::Vertice(QGraphicsItem * parent) :
QGraphicsItem(parent)
{
setFlag(ItemIsMovable);
setFlag(ItemIsSelectable);
setFlag(ItemSendsGeometryChanges);
}
void Vertice::paint(
QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setBrush(Qt::blue);
painter->setPen(Qt::darkGray);
painter->drawEllipse(-5,-5,10,10);
}
QVariant Vertice::itemChange(GraphicsItemChange change, const QVariant & value)
{
switch(change) {
case QGraphicsItem::ItemSelectedHasChanged:
qWarning() << "vertex: " + value.toString(); // never happened
break;
default:
break;
}
}
You say that your child items aren't getting mouse events, but they are. You can verify this by adding a void mousePressEvent(QGraphicsSceneMouseEvent * event) to Vertice and noticing that it is getting called.
Your problem is that Qt is ignoring the ItemIsMovable flag on a child QGraphicsItem. It's not even setting the flag when you ask.
You can verify this by changing your Vertice constructor:
Vertice::Vertice(QGraphicsItem * parent) :
QGraphicsItem(parent)
{
setFlag(ItemIsMovable);
Q_ASSERT(flags() & ItemIsMovable); // fails
setFlag(ItemIsSelectable);
setFlag(ItemSendsGeometryChanges);
}
Now why would that be? As the programming Jedi say: "use the source, Luke!"
https://qt.gitorious.org/qt/qtbase/source/7df3321f934e5bd618e2ad00bf801f2b7edd31df:src/widgets/graphicsview/qgraphicsitem.cpp#L1789
Notice that one of the things it does when flags are set is it offers that to itemChange to inspect with an ItemFlagsChange notification. Not only that, but it allows the flags to be overwritten by the result of that call. But look at your implementation of itemChange() on Vertice:
QVariant Vertice::itemChange(GraphicsItemChange change, const QVariant & value)
{
switch(change) {
case QGraphicsItem::ItemSelectedHasChanged:
qWarning() << "vertex: " + value.toString(); // never happened
break;
default:
break;
}
}
Uh-oh. No return result! Add this line to the end, as you have in your Item:
return QGraphicsItem::itemChange(change, value);
...and there you have it. Other notes:
Singular of "Vertices" is actually "Vertex"
If you have a case like this, think about paring it down from whatever specific program you are writing. If you can demonstrate the problem with one child item and one parent item, then why have a loop making four? If selection isn't part of the problem--and code for hiding and showing vertices need not be involved--then why involve it? It would be much better to use the code you provide to give required virtual methods like boundingRect() rather than make others write it to test. See Short, Self-Contained, Compilable Example
Qt source is fairly readable and well-organized, so do get into the habit of looking at it...!

Memory leak with post requests and QNetworkAccessManager

I'm making a program that uses lots of timer and, at intervals of 4 seconds, does an online post to a php script.
I'm coding in QtCreator 5.1. I use classes just like the ones below.
The one below just populates a task list, but throughout the course of 8 to 12 hours, the memory that the program takes up just keep rising and rising gradually.
What am I doing wrong while using this class?
I have to be able to keep posting online like I already am, about every 4 to 8 seconds.
Here's a simple class for taking care of one of my processes:
Header file: tasklistprocess.h
#ifndef TASKLISTPROCESS_H
#define TASKLISTPROCESS_H
#include <QThread>
#include <QtCore>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QListWidget>
#include <QTabWidget>
#include "globalhelper.h"
#include "securityinfo.h"
class TaskListProcess : public QThread
{
Q_OBJECT
public:
explicit TaskListProcess(QListWidget *obj_main, QTabWidget *tabs_main, QString user, QObject *parent = 0);
signals:
void upTaskStorage(int key,QHash<QString,QString> item);
private:
GlobalHelper gh;
Securityinfo sci;
QNetworkAccessManager *nam;
QNetworkRequest request;
QByteArray data;
// this is the disposable params for reusage through out the class
QUrlQuery params;
QString post_data;
QString user_name;
QTimer *tasklist_tmr;
bool get_task_list;
QListWidget *obj;
QTabWidget *tabs;
private slots:
void setTaskList();
void replyFinished(QNetworkReply *reply);
void sendPost(QString file_name, QUrlQuery params);
};
#endif // TASKLISTPROCESS_H`
Source file: tasklistprocess.cpp
#include "tasklistprocess.h"
TaskListProcess::TaskListProcess(QListWidget *obj_main, QTabWidget *tabs_main, QString user, QObject *parent) :
QThread(parent)
{
user_name = user;
get_task_list = false;
obj = obj_main;
tabs = tabs_main;
tasklist_tmr = new QTimer(this);
connect(this,SIGNAL(started()),this,SLOT(setTaskList()));
connect(tasklist_tmr,SIGNAL(timeout()),this,SLOT(setTaskList()));
nam = new QNetworkAccessManager(this);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
request.setRawHeader( "User-Agent" , "Mozilla Firefox" );
// here we connect up the data stream and data reply signals
connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
void TaskListProcess::setTaskList()
{
qDebug() << "Your task list was set";
bool in = false;
if(!(tasklist_tmr->isActive()))
{
tasklist_tmr->start(10000);
in = true;
}
if(!(get_task_list))
{
params.clear();
params.addQueryItem("user_name", user_name);
params.addQueryItem("logged_in", "1");
sendPost("getTaskList.php",params);
get_task_list = true;
}
else
{
if(post_data.contains("|*|"))
{
//here i retrieve a piece of information from a php script which is stored in a custom string format
// here we clear the list for the new data to be put in
if(obj->count()>0)
{
obj->clear();
}
int key = 0;
foreach(QString inner_task,post_data.split("|*|"))
{
QHash<QString,QString> task_cont;
//qDebug() << " ";
if(inner_task.contains("*,*"))
{
foreach(QString task_val,inner_task.split("*,*"))
{
if(task_val.contains("*=*"))
{
QStringList key_pairs = task_val.split("*=*");
task_cont.insert(key_pairs[0],key_pairs[1]);
if(key_pairs[0] == "tt")
{
QString val_in;
if(key_pairs[1].length()>10)
{
// this sets the title to the shortened version
// if the string length is too long
val_in = key_pairs[1].left(10) + "....";
}
else
{
val_in = key_pairs[1];
}
obj->addItem("Task :" + QString::fromUtf8(key_pairs[1].toStdString().c_str()));
}
}
}
}
//task_storage.insert(key,task_cont);
emit upTaskStorage(key,task_cont);
key ++;
}
}
get_task_list = false;
}
// here we're checking to see if they are looking at the task tab so it doesn't keep changing
// back and forth between the tabs
bool change = true;
if(tabs->currentIndex() != 0)
{
change = false;
}
if(change)
{
tabs->setCurrentIndex(0);
}else if(in)
{
tabs->setCurrentIndex(0);
}
}
void TaskListProcess::replyFinished(QNetworkReply *reply)
{
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error in" << reply->url() << ":" << reply->errorString();
return;
}
QString data = reply->readAll().trimmed();
post_data = data;
if(get_task_list)
{
setTaskList();
}
}
void TaskListProcess::sendPost(QString file_name, QUrlQuery params)
{
post_data = "";
QUrl url(sci.getHost() + file_name);
url.setQuery(params);
data.clear();
data.append(params.toString().toUtf8());
request.setUrl(url);
nam->post(request, data);
}
From the Qt docs http://qt-project.org/doc/qt-5.1/qtnetwork/qnetworkaccessmanager.html
Note: After the request has finished, it is the responsibility of the
user to delete the QNetworkReply object at an appropriate time. Do not
directly delete it inside the slot connected to finished(). You can
use the deleteLater() function.
I would suggest calling reply->deleteLater() in your replyFinished() method.
You should call deleteLater() for an QNetworkReply object after use.
Note: After the request has finished, it is the responsibility of the user to delete the QNetworkReply object at an appropriate time. Do not directly delete it inside the slot connected to finished(). You can use the deleteLater() function.
More information here: http://harmattan-dev.nokia.com/docs/library/html/qt4/qnetworkaccessmanager.html
Thank you everyone for the hel.
It was very simply the "deleteLater()" on the reply in the
void replyFinished(QNetworkReply *reply)
{
}
and it should have looked like this
void replyFinished(QNetworkReply *reply)
{
// after all of your processing
reply->deleteLater();
}
it was such a small problem but one that drove me crazy for a long time so i hope this helps