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

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.

Related

Color channels are changing using Qt QImage with data and I don't know why

I have written a function in Qt to extract the data out of an image for the purpose of manipulating it.
I then have another function to reinsert the data back to an image and display it. The problem I am having is that even if I do no manipulation on the pixel data other than extract and reinsert, it is still changing the data. On a yellow image it changes it to turquoise blue when it should remain yellow.
I am including the function code to extract and reinsert as specimen code. I can include more if it is needed such as the display function etc...Does anyone know if I am doing something wrong?
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
filter = "All Picture Files (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"
";; Bitmap Files (*.bmp) ;; JPEG (*.jpg *.jpeg) ;; PNG (*.png) ;; TIFF (*.tif *.tiff)";
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::importImage()
{
importCancelled = false;
QString filename = QFileDialog::getOpenFileName(nullptr, QObject::tr("Import Image"), "", filter);
if(!filename.isEmpty()){
image.load(filename);
image = image.convertToFormat(QImage::Format_RGBA8888);
}
else {
importCancelled = true;
if(importCancelled){
QString cleanPlateCancelled = "Operation Cancelled";
ui->statusBar->showMessage(cleanPlateCancelled,5000);
return;
}
}
}
void MainWindow::scaleImage()
{
if (image.isNull()){
return;
}
else {
image = image.scaledToHeight(ui->view->height(), Qt::TransformationMode::SmoothTransformation);
}
}
void MainWindow::displayImage()
{
if (image.isNull()){
return;
}
else {
scene = new QGraphicsScene;
showImage = new QGraphicsPixmapItem(QPixmap::fromImage(image));
scene->addItem(showImage);
ui->view->setScene(scene);
}
}
void MainWindow::rgbaExtraction()
{
numberOfBytes = static_cast<uint>(image.sizeInBytes());
auto const imageData = image.bits();
rgba = std::vector<uchar>(numberOfBytes,0);
rgbaReset = std::vector<uchar>(numberOfBytes,0);
for (uint i{0}; i < numberOfBytes; ++i) {
rgbaReset[i] = rgba[i] = imageData[i];
}
}
void MainWindow::rgbaInsertion()
{
auto *imageData = new uchar[numberOfBytes];
for (uint i{0};i < numberOfBytes;++i) {
imageData[i] = rgba[i];
}
image = QImage(imageData, image.width(), image.height(), QImage::Format_RGBA8888);
}
void MainWindow::on_importButton_clicked()
{
importImage();
scaleImage();
displayImage();
rgbaExtraction();
}
void MainWindow::on_quitButton_clicked()
{
QApplication::quit();
}
void MainWindow::sceneUpdater()
{
showImage->setPixmap(QPixmap::fromImage(image));
scene->update();
ui->view->update();
}
void MainWindow::on_redSlider_valueChanged(int value)
{
QString redString = QString::number(value);
ui->redLabel->setText(redString);
redDelta = value;
colorRed();
rgbaInsertion();
sceneUpdater();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QImage>
#include <QFileDialog>
#include <string>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_importButton_clicked();
void on_quitButton_clicked();
void on_redSlider_valueChanged(int value);
private:
QGraphicsPixmapItem *showImage;
QGraphicsScene *scene;
QString filter;
QImage image;
bool importCancelled;
QStatusBar *statusBar;
uint numberOfBytes;
std::vector<uchar> rgba;
std::vector<uchar> rgbaReset;
int redDelta{0};
int greenDelta{0};
int blueDelta{0};
int opacityDelta{0};
void importImage();
void scaleImage();
void displayImage();
void rgbaExtraction();
void rgbaInsertion();
void sceneUpdater();
void colorRed(); // Implemented in color.cpp
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
color.cpp
#include <mainwindow.h>
void MainWindow::colorRed()
{
for (uint i{0}; i < rgba.size()*sizeof (rgba[i]);i+=4) {
if(rgbaReset[i] + static_cast<uchar>(redDelta)>=255){
rgba[i] = 255;
}
else {
rgba[i] = rgbaReset[i];// + static_cast<uchar>(redDelta);
}
}
}
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 problem is in scaleImage(), because scaledToHeight() returns another image format. You may omit the scale operation, or convert the returned image to Format_RGBA8888:
void MainWindow::scaleImage()
{
if (image.isNull()){
return;
}
else {
image = image.scaledToHeight(ui->view->height(), Qt::TransformationMode::SmoothTransformation)
.convertToFormat(QImage::Format_RGBA8888);
}
}
My recomendation is to add some instrumentation after each image manipulation to check that it has the expected format:
qDebug() << Q_FUNC_INFO << "image format:" << image.format();

Unexpected behaviour with QMouseMoveEvent and QKeyEvent modifiers

I am encountering unexpected behaviour in my code.
I have a QGraphicsView containing a QGraphicsScene. Now I want to detect the mouse wheel for zooming the view and mouse moving for moving items in the scene, the latter only while controll is pressed. Now I have two Problems:
MouseMoveEvent is called even when the mouse is not moved but only the mouse wheel.
Moving with and without controll pressed works fine but when I stop moving while controll is pressed and continue using the mouse wheel not only the mousemoveevent is called but also the controllmodifier is still active. What is the problem?
main.cpp
#include "ppi.h"
#include <QtGui/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
PPI w;
w.show();
return a.exec();
}
ppi.h
#ifndef PPI_H
#define PPI_H
#include <QtGui/QMainWindow>
#include <QGraphicsView>
#include <QDebug>
#include <QWheelEvent>
#include "ui_ppi.h"
#include "ppiView.h"
#include "ppiscene.h"
class PPI : public QMainWindow
{
Q_OBJECT
public:
PPI(QWidget *parent = 0, Qt::WFlags flags = 0);
~PPI();
int i;
private:
Ui::ppiClass ui;
PPIScene* ppiScene;
protected slots:
void onZoom(QWheelEvent *event);
void onMouseMoved(QGraphicsSceneMouseEvent *event);
};
#endif // PPI_H
ppi.cpp
#include "ppi.h"
PPI::PPI(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
ppiScene = new PPIScene(this);
connect(ppiScene, SIGNAL(mouseMoved(QGraphicsSceneMouseEvent*)), this, SLOT(onMouseMoved(QGraphicsSceneMouseEvent*)));
connect(ui.gVPPI, SIGNAL(zoom(QWheelEvent*)), this, SLOT(onZoom(QWheelEvent*)));
ppiScene->setSceneRect(0,0,1024,1024);
ui.gVPPI->setScene(ppiScene);
ui.gVPPI->setMouseTracking(true);
i = 0;
}
PPI::~PPI()
{
}
void PPI::onZoom(QWheelEvent *event)
{
if(event->delta() > 0)
ui.gVPPI->scale(1.01, 1.01);
else
ui.gVPPI->scale(1/1.01, 1/1.01);
}
void PPI::onMouseMoved(QGraphicsSceneMouseEvent *event)
{
i++;
qDebug() << "slot" << i << event->modifiers();
if(event->modifiers() & Qt::ControlModifier)
{
qDebug() << "ctrl pressed";
}
}
ppiview.h
#ifndef PPIVIEW_H
#define PPIVIEW_H
#include <QGraphicsView>
#include <QMouseEvent>
class PPIView : public QGraphicsView
{
Q_OBJECT
public:
PPIView(QWidget * parent = 0);
~PPIView();
private:
void wheelEvent(QWheelEvent *event);
signals:
void zoom(QWheelEvent *event);
};
#endif // PPIVIEW_H
ppiview.cpp
#include "ppiview.h"
PPIView::PPIView(QWidget * parent)
: QGraphicsView(parent)
{
}
PPIView::~PPIView()
{
}
void PPIView::wheelEvent(QWheelEvent *event)
{
emit zoom(event);
}
ppiscene.h
#ifndef PPISCENE_H
#define PPISCENE_H
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
class PPIScene : public QGraphicsScene
{
Q_OBJECT
public:
PPIScene(QObject *parent);
~PPIScene();
int i;
private:
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
signals:
void mouseMoved(QGraphicsSceneMouseEvent *event);
};
#endif // PPISCENE_H
ppiscene.cpp
#include "ppiscene.h"
PPIScene::PPIScene(QObject *parent)
: QGraphicsScene(parent)
{
i = 0;
}
PPIScene::~PPIScene()
{
}
void PPIScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
i++;
qDebug() << "signal" << i << event->modifiers();
emit mouseMoved(event);
}
It is really strange. It looks like the Qt::KeyboardModifiers status, which QGraphicsSceneMouseEvent::modifiers returns, is only updated, when the mouse is physically moved. What is even more strange, is that in your code QGraphicsSceneMouseEvents of type QGraphicsSceneMouseMove are sent even when the mouse is not moved at all, but only the wheel is turned. Maybe the relative movement due to your scaling counts as movement, but not as movement, which updates the modifiers.
I was able to reproduce your problem: The status of the modifiers don't change unless the mouse is physically moved.
Fortunately there is an easy workaround. In
void PPI::onMouseMoved(QGraphicsSceneMouseEvent *event)
{
i++;
qDebug() << "slot" << i << event->modifiers();
if(event->modifiers() & Qt::ControlModifier)
{
qDebug() << "ctrl pressed";
}
}
replace:
if(event->modifiers() & Qt::ControlModifier)
with:
if(QApplication::queryKeyboardModifiers() & Qt::ControlModifier)
QApplication::queryKeyboardModifiers() is updated immediately when you press or release the control key.

Horde3D Particle System not rendering in Qt OpenGL

Horde3d come with 2 samples, compiled with GLFW. One of them, Knight, shows a particle emitter. I've ported the samples to Qt, with a thin layer I wrote that leave unchanged the applicative code (i.e. scene setup, rendering and events handling).
Indeed, the functionality is ok, except the particle emitter doesn't show. I can't see anything specific in GLFW initialization, and I tried some setting I found in Qt, without success. Horde3d takes care of OpenGL interface, and expose a higher level, clean C interface. Any clue?
EDIT : Most Rilevant Sources of qtKnight.pro
here (cleaned :) main.cpp
#include "glwidget.h"
#include <QApplication>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
GLWidget glw;
glw.show();
return app.exec();
}
here glWidget.h
#ifndef GL_WIDGET_H
#define GL_WIDGET_H
#include <QtOpenGL>
#include <QTimer>
#include <QKeyEvent>
#include <Horde3D.h>
#include <Horde3DUtils.h>
#include <sstream>
#include <app.h>
class GLWidget : public QGLWidget, Application {
Q_OBJECT
public:
GLWidget();
~GLWidget();
QSize minimumSizeHint() const { return sizeHint(); }
QSize sizeHint() const { return QSize(640, 480); }
protected:
void initializeGL();
void paintGL();
void resizeGL(int width, int height);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void keyPressEvent(QKeyEvent *e) { keyEvent(e, true); QGLWidget::keyPressEvent(e); }
void keyReleaseEvent(QKeyEvent *e) { keyEvent(e, false); QGLWidget::keyReleaseEvent(e); }
void keyEvent(QKeyEvent *, bool);
public slots:
void appLoop() { updateGL(); }
private:
QPoint lastPos;
QTimer evloop;
};
#endif
and here glWidget.cpp
#include "glwidget.h"
#include <stdexcept>
#include <QtDebug>
#include <QTextStream>
#include <QGLFormat>
GLWidget::GLWidget() :
QGLWidget(QGLFormat(QGL::AlphaChannel | QGL::SampleBuffers)),
Application("/home/carlo/horde3d/SDK_1.0.0_Beta5/Horde3D/Binaries/Content")
{
connect(&evloop, SIGNAL(timeout()), this, SLOT(appLoop()));
evloop.start(0);
}
GLWidget::~GLWidget()
{
h3dutDumpMessages();
h3dRelease();
}
void GLWidget::initializeGL()
{
if (!init())
throw std::runtime_error("Could not initialize renderer");
}
void GLWidget::paintGL()
{
keyStateHandler();
mainLoop(30);
}
void GLWidget::resizeGL(int width, int height)
{
Application::resize(width, height);
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
lastPos = event->pos();
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
QPoint cPos = event->pos();
float dX = cPos.x() - lastPos.x(); //event->x() - lastPos.x();
float dY = cPos.y() - lastPos.y(); //event->y() - lastPos.y();
Application::mouseMoveEvent(dX, dY);
lastPos = cPos;
}
void GLWidget::mouseReleaseEvent(QMouseEvent * /* event */)
{
}
void GLWidget::keyEvent(QKeyEvent *k, bool on_off)
{
#define setK(X,Y) case Qt::X: setKeyState(Y, on_off); break;
#define setF(X) case Qt::Key_##X: setKeyState(X, on_off); break;
#define R(X, Y) (v >= #X[0] && v <= #Y[0])
int v = k->key();
switch (v) {
case Qt::Key_F1: if (on_off) showFullScreen(); break;
case Qt::Key_F2: if (on_off) showNormal(); break;
setF(F3)
setF(F6)
setF(F7)
setF(F8)
setK(Key_Space, SP)
default:
if (R(A, Z) || R(0, 9))
setKeyState(v, on_off);
}
}
Since you say it is only the particles that aren't shown, it could have to do with alpha blending. I also saw from your code that you don't specify a format when constructing the QGLWidget, in which case the default format is used which explicitly disables the alpha channel.
Though I don't know if this has any effect (shouldn't there always be an A in RGBA?), but maybe this really requests a pixel format where there is no storage for the A channel, in which case things like alpha blending (used for the transparent particles) won't work.
So just try to request it explicitly by using an appropriate format in the QGLWidget constructor:
GLWidget::GLWidget()
: QGLWidget(QGLFormat(QGL::AlphaChannel))
You actually were on the right track with your outcommented QGLFormat argument, but it hasn't anything to do with the HasOverlay option, which you don't really need, as Horde3d does it's own overlay rendering.

QT hangs my toolbar and its buttons

I've created 2 classes, each:
has QWidget as a parent
has Q_OBJECT macros
inits some actions, creates menubar and toolbar, and connects actions to them
Then I created the main program file, created QMainWindow, and init my two classes by qmainwnd pointer.
And what I've got - menu works, the second toolbar works, but the first toolbar (created by class 1) doesn't respond to mouse clicks.
What happed with it? Why I can not even move this first toolbar or click its buttons?
Here a sample:
main.cpp
#include <QApplication>
#include <QMainWindow>
#include "CModDocument.h"
#include "CModEditor.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow wnd;
// init CA
CModDocument a(&wnd);
// init CB
CModEditor b(&wnd);
wnd.show();
return app.exec();
}
CModDocument.h
#ifndef CMODDOCUMENT_H
#define CMODDOCUMENT_H
#include <QWidget>
QT_BEGIN_NAMESPACE
class QAction;
class QToolBar;
class QMainWindow;
QT_END_NAMESPACE
class CModDocument: public QWidget
{
Q_OBJECT
public:
CModDocument(QWidget *parent = 0);
QMainWindow *getMainWnd();
public slots:
void newFile();
void open();
bool save();
bool saveAs();
private:
void createActions();
void createToolBars();
void interCom();
QMainWindow *mainWnd;
QToolBar *fileToolBar;
QAction *newAct;
QAction *openAct;
QAction *saveAct;
QAction *saveAsAct;
};
#endif // CMODDOCUMENT_H
CModDocument.cpp
#include <QtGui>
#include <QDebug>
#include "CModDocument.h"
CModDocument::CModDocument( QWidget *parent )
: QWidget( parent )
, mainWnd( (QMainWindow*)parent )
{
createActions();
createToolBars();
interCom();
mainWnd->statusBar()->showMessage(tr("Ready"));
}
void CModDocument::newFile()
{
qDebug() << "newFile";
}
void CModDocument::open()
{
qDebug() << "open";
}
bool CModDocument::save()
{
qDebug() << "save";
bool retVal;
return retVal;
}
bool CModDocument::saveAs()
{
qDebug() << "saveAs";
bool retVal;
return retVal;
}
void CModDocument::createActions()
{
newAct = new QAction(tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
openAct = new QAction(tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
saveAct = new QAction(tr("&Save"), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save the document to disk"));
saveAsAct = new QAction(tr("Save &As..."), this);
saveAsAct->setShortcuts(QKeySequence::SaveAs);
saveAsAct->setStatusTip(tr("Save the document under a new name"));
}
void CModDocument::createToolBars()
{
fileToolBar = mainWnd->addToolBar(tr("File"));
fileToolBar->addAction(newAct);
fileToolBar->addAction(openAct);
fileToolBar->addAction(saveAct);
}
void CModDocument::interCom()
{
connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
}
CModEditor.h
#ifndef CMODEDITOR_H
#define CMODEDITOR_H
#include <QWidget>
// #include "CModEdiWidget.h"
QT_BEGIN_NAMESPACE
class QMainWindow;
class QAction;
class QMenu;
class QMenuBar;
class QToolBar;
QT_END_NAMESPACE
class CModEditor : public QWidget
{
Q_OBJECT
public:
CModEditor(QWidget *parent = 0);
public slots:
void cut();
private:
void createActions();
void createToolBars();
void interCom();
QAction *cutAct;
QToolBar *editToolBar;
// parent
QMainWindow *mainWnd;
};
#endif
CModEditor.cpp
#include <QtGui>
#include <QDebug>
#include "CModEditor.h"
CModEditor::CModEditor(QWidget *parent)
: QWidget(parent)
, mainWnd( (QMainWindow*)parent )
{
createActions();
createToolBars();
interCom();
}
void CModEditor::cut()
{
qDebug() << "cut";
}
void CModEditor::createActions()
{
cutAct = new QAction(tr("Cu&t"), this);
cutAct->setShortcuts(QKeySequence::Cut);
cutAct->setStatusTip(tr("Cut the current selection's contents to the clipboard"));
}
void CModEditor::createToolBars()
{
editToolBar = mainWnd->addToolBar(tr("Edit"));
editToolBar->addAction(cutAct);
editToolBar->setIconSize(QSize(16, 16));
}
void CModEditor::interCom()
{
connect(cutAct, SIGNAL(triggered()), this, SLOT(cut()));
}
build.pro
CONFIG -= app_bundle
HEADERS = CModDocument.h CModEditor.h
SOURCES = CModDocument.cpp CModEditor.cpp main.cpp
The problem seems to be that you are trying to configure the QMainWindow as the parent to two QWidgets. I modified your main() function as follows and it worked:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow wnd;
QWidget w;
// init CA
CModDocument a(&wnd, &w);
// init CB
CModEditor b(&wnd, &w);
wnd.show();
return app.exec();
}
Notice the new QWidget w that parents a and b. I'm not even sure my approach is adequate (it probably isn't). I think it is better to add a QLayout to w and add a and b to that QLayout. Then you could set w as wnd's central widget.

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