Paste operation in QGraphicsView - qt

I am implenting copy paste operation in QGraphicsView to different entites like circle, point, ellipse etc. Applied copy operation but unable to get how to apply paste operation for it. Please help me out solve the problem. My slot for copy appears as follows:
cadgraphicsscene.cpp
void CadGraphicsScene::copy()
{
selectItems();
}
void CadGraphicsScene::selectItems()
{
// refresh record of selected items and their starting positions
selectedItems.clear();
foreach (QGraphicsItem *item, itemList)
{
if (item->isSelected())
{
if (dynamic_cast<QGraphicsItem *>(item))
{
selectedItems.append(qMakePair(
dynamic_cast<QGraphicsItem *>(item),
item->scenePos()));
}
}
}
}
cadgraphicsscene.h
#ifndef CADGRAPHICSSCENE_H
#define CADGRAPHICSSCENE_H
#include <QGraphicsScene>
#include <QXmlStreamWriter>
#include <QUndoStack>
#include "cadcommandadd.h"
#include "cadcommanddelete.h"
#include "cadcommandmove.h"
class CadGraphicsScene : public QGraphicsScene
{
Q_OBJECT
public:
explicit CadGraphicsScene(QObject *parent, QUndoStack *);
enum Mode { NoMode, PointMode, LineMode, CircleMode, EllipseMode, TextMode };
QFont font() const
{
return myFont;
}
QColor textColor() const
{
return myTextColor;
}
void setTextColor(const QColor &color);
void setFont(const QFont &font);
void deleteItems();
void copy();
void writeStream(QXmlStreamWriter *stream);
void readStream(QXmlStreamReader *stream);
public slots:
void setMode(Mode mode);
void selectItems();
void editorLostFocus(mText *item);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent);
void setFlags();
void areItemsSelectable(bool);
signals:
void textInserted(QGraphicsTextItem *item);
void itemSelected(QGraphicsItem *item);
private:
Mode entityMode;
QUndoStack *mUndoStack;
bool mFirstClick;
bool mSecondClick;
bool mThirdClick;
bool mPaintFlag;
QVector<QPointF> stuff;
QPointF start_p, mid_p, end_p, move_p, check_p;
QPen paintpen, linePen;
QList<QGraphicsItem *> itemList;
Point *pointItem;
Line *lineItem;
Circle *circleItem;
Ellipse *ellipseItem;
mText *textItem;
QColor myTextColor;
QFont myFont;
typedef QPair<QGraphicsItem *, QPointF> itemPos;
QList<itemPos> selectedItems;
};
#endif // CADGRAPHICSSCENE_H

Related

MouseMoveEvent stops being called

I'm using QCustomPlot (plot_ object) on QQuickPaintedItem (SinePlot class) so I can use it in QML. In mousePressEvent I collect initial point and in mouseMoveEvent I'm making calculations to add new points and updating cursor point:
void SinePlot::mousePressEvent(QMouseEvent* event)
{
prevPoint_ = event->globalPos();
}
void SinePlot::mouseMoveEvent(QMouseEvent* event)
{
QPointF tmp = event->globalPos();
qreal prop = (prevPoint_.x() - tmp.x()) / width();
if(prop > 0)
{
data_->shiftLeft(prop);
} else {
data_->shiftRight(prop);
}
plot_->xAxis->setRange(data_->minX, data_->maxX);
...
prevPoint_ = tmp;
update();
}
I have also trying to use pos() and localPos() but it does not make any difference, here is what I got:
As you can see mouseMoveEvent stops being called after some time(before releasing) and moving cursor does not call it.
Here is minimal reproducible example:
#ifndef SINEPLOT_H
#define SINEPLOT_H
#include "qcustomplot.h"
#include <QtQuick>
#include <QDebug>
class SinePlot : public QQuickPaintedItem
{
Q_OBJECT
public:
explicit SinePlot(QQuickItem* parent=nullptr)
{
setAcceptedMouseButtons(Qt::AllButtons);
plot_ = new QCustomPlot();
plot_->setInteractions(QCP::iRangeDrag);
plot_->addGraph();
}
virtual ~SinePlot()
{
delete plot_;
}
void paint(QPainter* painter)
{
QPicture picture;
QCPPainter qcpPainter;
qcpPainter.begin(&picture);
plot_->toPainter(&qcpPainter, width(), height());
qcpPainter.end();
picture.play(painter);
};
protected:
virtual void mousePressEvent(QMouseEvent* event) {};
virtual void mouseMoveEvent(QMouseEvent* event)
{
qDebug() << "mouse move";
};
private:
QCustomPlot* plot_;
};
#endif
In my case I got "mouse move" ~10 times.

how to get drop events of object which is placed in graphic scene?

i have graphic view(QGraphics view) setted scene(QGraphic scene) i am dropping objects on scene its working fine, i have to assign parameter for dropped object by dragging parameter from parameter list .i have implemented drag drop events of object.but when i am dragging parameter from param list non- acceptance symbol on object.how to assign param to object by dropping ? Any other suggestions and examples are welcome where i can get ideas to implementation.
image of gui
speedometer.cpp
#include <QMimeData>
SpeedoMeter::SpeedoMeter( QWidget *parent ):
QwtDial( parent ),
d_label( "km/h" )
{
setAcceptDrops(true);
}
void SpeedoMeter::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat(paramlistMimeType()))
{
qDebug()<<"dragenter event in speedo" ;
event->accept();
}
}
void SpeedoMeter::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat(paramlistMimeType()))
{
qDebug()<<"dragmove event in speedo" ;
event->acceptProposedAction();
}
}
void SpeedoMeter::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasFormat(paramlistMimeType()))
{
qDebug()<<"dragmove event in speedo" ;
event->accept();
}
}
The following example shows how to implement the logic to accept the drag-and-drop:
speedometer.h
#ifndef SPEEDOMETER_H
#define SPEEDOMETER_H
#include <qwt_dial.h>
class SpeedoMeter : public QwtDial
{
public:
SpeedoMeter(QWidget *parent=nullptr);
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void paintEvent(QPaintEvent *event);
private:
QString d_label;
};
#endif // SPEEDOMETER_H
speedometer.cpp
#include "speedometer.h"
#include <qwt_dial_needle.h>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QPainter>
SpeedoMeter::SpeedoMeter(QWidget *parent):
QwtDial(parent),
d_label( "km/h" )
{
setAcceptDrops(true);
QwtDialSimpleNeedle *nd = new QwtDialSimpleNeedle(QwtDialSimpleNeedle::Arrow, Qt::white, Qt::red);
setNeedle(nd);
setValue(80);
}
void SpeedoMeter::dragEnterEvent(QDragEnterEvent *event)
{
if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
event->acceptProposedAction();
}
void SpeedoMeter::dropEvent(QDropEvent *event)
{
const QMimeData *mimedata = event->mimeData();
if(mimedata->hasFormat("application/x-qabstractitemmodeldatalist")){
QString text;
// https://stackoverflow.com/questions/1723989/how-to-decode-application-x-qabstractitemmodeldatalist-in-qt-for-drag-and-drop
QByteArray encoded = mimedata->data("application/x-qabstractitemmodeldatalist");
QDataStream stream(&encoded, QIODevice::ReadOnly);
while (!stream.atEnd()) {
int row, col;
QMap<int, QVariant> roleDataMap;
stream >> row >> col >> roleDataMap;
if(roleDataMap.contains(Qt::DisplayRole)){
text = roleDataMap[Qt::DisplayRole].toString();
break;
}
}
// your text
d_label = text;
update();
}
}
void SpeedoMeter::dragMoveEvent(QDragMoveEvent *event)
{
if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
event->accept();
}
void SpeedoMeter::paintEvent(QPaintEvent *event)
{
// https://stackoverflow.com/questions/43904204/qwt-dial-show-unit
QwtDial::paintEvent(event);
QPainter painter(this);
painter.setPen(Qt::black);
QFont font;
font.setPointSize(11);
painter.setFont(font);
QString text = QString("%1 %2").arg(value()).arg(d_label);
QPoint c = rect().center();
QSize Size = painter.fontMetrics().size(Qt::TextSingleLine, text);
painter.drawText(QPointF(c.x() -Size.width()/2, c.y() + 2.5*Size.height()), text);
}
main.cpp
#include "speedometer.h"
#include <QApplication>
#include <QGraphicsView>
#include <QHBoxLayout>
#include <QListWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QHBoxLayout *layout = new QHBoxLayout(&w);
QListWidget listWidget;
listWidget.setDragDropMode(QAbstractItemView::DragOnly);
listWidget.addItems({"km/h", "ft/s", "m/s", "miles/h"});
QGraphicsView view;
QGraphicsScene scene;
view.setScene(&scene);
SpeedoMeter speed;
scene.addWidget(&speed);
layout->addWidget(&listWidget);
layout->addWidget(&view);
w.show();
return a.exec();
}
In the following link you can find the complete example.

Cannot implement Drag and Drop for TextItem

this is my first try trying to use Drag&Drop feature of Qt. I'm a beginner, I made my first subclassing this week although I have made other 2 Qt programs in the past.
I need a movable by Drag&Drop QGraphicsTextItem to show on a QGraphicsView that is connected to the corresponding QGraphicScene. So I can retrieve the new position of the item.
I have looked at the animated robot example and this link: http://www.qtcentre.org/threads/50028-Drag-and-Drop-QGraphicsTextItem
The code of the link above, looked well for my. So I reimplemented it but when building, the compiler shows all kind of errors I´m not sure how to overcome. I don't know where to start, and don't know what piece of code is incorrect...
examples of errors appearing:
error: no matching function for call to 'GraphicsTextItem::setCursor(Qt::CursorShape)'
setCursor(Qt::OpenHandCursor);
^
error: invalid use of incomplete type 'class QGraphicsSceneDragDropEvent'
if(event->mimeData()->hasText())
^
error: forward declaration of 'class QGraphicsSceneDragDropEvent'
class QGraphicsSceneDragDropEvent;
^
I'll leave the code:
Header:
#ifndef GRAPHICSTEXTITEM_H
#define GRAPHICSTEXTITEM_H
#include <QGraphicsTextItem>
class GraphicsTextItem : public QGraphicsTextItem
{
Q_OBJECT
public:
GraphicsTextItem(QGraphicsItem *parent = 0);
protected:
void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
void dropEvent(QGraphicsSceneDragDropEvent *event);
void mousePressEvent(QGraphicsSceneMouseEvent *);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
private:
bool dragOver;
};
//! [0]
#endif // GRAPHICSTEXTITEM_H
and the Implementation:
#include <graphicstextitem.h>
#include <QDrag>
//#include <QGraphicsScene>
GraphicsTextItem::GraphicsTextItem(QGraphicsItem *parent)
:QGraphicsTextItem(parent)
{
//setFlag(QGraphicsItem::ItemIsSelectable);
setFlag(QGraphicsItem::ItemIsMovable);
setTextInteractionFlags(Qt::TextEditorInteraction);
setAcceptedMouseButtons(Qt::LeftButton);
setAcceptDrops(true);
setCursor(Qt::OpenHandCursor);
}
void GraphicsTextItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
if(event->mimeData()->hasText())
{
event->setAccepted(true);
update();
dragOver = true;
}
else
event->setAccepted(false);
}
void GraphicsTextItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
Q_UNUSED(event);
dragOver = false;
update();
}
void GraphicsTextItem::dropEvent(QGraphicsSceneDragDropEvent *event)
{
event->setAccepted(true);
//qDebug() << "I dropped it";
dragOver = false;
update();
}
void GraphicsTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event);
setCursor(Qt::ClosedHandCursor);
}
void GraphicsTextItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton)).length()
< QApplication::startDragDistance())
return;
QDrag *drag = new QDrag(event->widget());
QMimeData *mime = new QMimeData;
mime->setText(this->toPlainText());
drag->setMimeData(mime);
drag->exec();
setCursor(Qt::OpenHandCursor);
}
void GraphicsTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event);
setCursor(Qt::OpenHandCursor);
}
The error message is telling you that there is a forward declaration somewhere in your code, although that is not true based on the code you have shown so far.
Either way, for accessingt members of your heap object, you need more than just forward declaration. You are missing this include:
#include <QGraphicsSceneDragDropEvent>

QLineEdit mouseEnter() and mouseExit() events

I want to subclass QLineEdit to add it some signals like mouseEnter() and mouseExit() to become informed when the mouse courser is over the widget and when leaves it.
I could write mouseEnter() like below.
class MyLineEdit:public QLineEdit{
//
// ..
//
protected:
void mouseMoveEvent(QMouseEvent *e);
signals:
void mouseEnter();
}
void MyLineEdit::mouseMoveEvent(QMouseEvent *e)
{
emit mouseEnter();
QLineEdit::mouseMoveEvent(e);
}
It works correctly.
How can I write mouseExit()?
leaveEvent is not a very good name!
#include <QtGui>
#include <QEvent>
class Editor : public QLineEdit
{
Q_OBJECT
public:
void leaveEvent(QEvent *);
signals:
void mouseLeave();
};
void Editor::leaveEvent(QEvent *e);
{
qDebug() << "Mouse has left the building..";
emit mouseLeave();
}

Extending QGraphicsScene

I am extending QGraphicsItem to be added to a extended QGraphicsSene. when I added the extended item to the scene and the scene to the graphics view in the normal way it shows the image but when I added the image as follows it does not show. could some one please check this out and tell me the issue.
header
#ifndef IMAGEMAP_H
#define IMAGEMAP_H
#include <QGraphicsItem>
#include <QGraphicsScene>
class ScanImage : public QGraphicsItem
{
public:
ScanImage(const QString imgsrc);
~ScanImage();
void setImageSource(const QString is);
QString imageSource();
QRectF boundingRect() const;
void paint( QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
private:
QString imgsrc;
};
class ImageHolder : public QGraphicsScene
{
public:
ImageHolder();
~ImageHolder();
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent);
private:
QRectF selectedRect;
};
#endif //
source
#include "imagemap.h"
#include "QtGui"
ScanImage::ScanImage(const QString is)
{
imgsrc=is;
update();
}
ScanImage::~ScanImage()
{
}
ImageHolder::ImageHolder()
{
setSceneRect(0.0,0.0,512.0,512.0);
ScanImage im("2.jpg");
im.setZValue(1.0);
im.setVisible(true);
addItem(&im);
}
ImageHolder::~ImageHolder()
{
}
void ScanImage::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() <<event->pos();
}
void ImageHolder::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() <<event->scenePos().rx();
selectedRect.setTopLeft(event->scenePos());
}
void ImageHolder::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
qDebug() <<mouseEvent->scenePos().ry();
selectedRect.setBottomRight(mouseEvent->scenePos());
addRect ( selectedRect);
}
QRectF ScanImage::boundingRect() const
{
return QRectF(0.0, 0.0, 512.0, 512.0);
}
void ScanImage::paint( QPainter* painter,
const QStyleOptionGraphicsItem*,
QWidget* )
{
QRectF target(0.0, 0.0, 512.0, 512.0);
QRectF source(0.0, 0.0, 512.0, 512.0);
painter->drawImage(target, QImage(imgsrc),source);
}
void ScanImage::setImageSource(QString is)
{
imgsrc = is;
}
QString ScanImage::imageSource()
{
return imgsrc;
}
main
int main(int argv, char* argc[])
{
QApplication app(argv,argc);
ImageHolder scene;
QGraphicsView view(&scene);
view.resize(512,512);
view.show();
return app.exec();
}
You are adding a QGraphicsItem allocated as a local variable on the QGraphicsScene constructor's stack. Once the constructor is finished, the objects on its stack are automatically deallocated (i.e. deleted) and in your case removed from the scene. Use new operator to create the item.

Resources