Namespaces
Variants
Actions

Line drawing with mouse coordinate in Qt

Jump to: navigation, search
Article Metadata

Tested with
Devices(s): S60 Emulator

Compatibility
Platform(s): Qt

Article
Keywords: QGraphicsScene,QGraphicsView
Created: mind_freak (23 Jun 2009)
Last edited: hamishwillee (11 Oct 2012)

Contents

Overview

This code will show you the line drawing in the QGraphicsScene by getting the end points of line with the help of mouseMove() Event.

When the mouse is moved on the widget at that time the mouse coordinates are catched and use to draw line from center to that specific coordinate.

Source Code

Source.h

#ifndef EVE1_H
#define EVE1_H
 
#include <QtGui/QWidget>
#include<QMouseEvent>
#include<QGraphicsLineItem>
#include<QGraphicsScene>
#include<QGraphicsView>
#include<QGraphicsItem>
#include<QHBoxLayout>
class EVE1 : public QWidget
{
Q_OBJECT
 
public:
EVE1(QWidget *parent = 0);
~EVE1();
 
private:
QHBoxLayout *lay;
QGraphicsScene *scene;
QGraphicsItem *item;
QGraphicsView *view;
private slots:
void mouseMoveEvent(QMouseEvent *);
};
 
#endif // EVE1_H

Source.cpp

#include "eve1.h"
#include "ui_eve1.h"
 
EVE1::EVE1(QWidget *parent)
: QWidget(parent)
{
lay=new QHBoxLayout(this);
scene=new QGraphicsScene(this);
scene->setSceneRect(0,0,250,250);
view=new QGraphicsView(scene,this);
view->show();
setMouseTracking(1);//Enable Mouse tracking on widget.
lay->addWidget(view);
setLayout(lay);
 
}
 
EVE1::~EVE1()
{
// No need to delete any object that has got a parent which is properly deleted.
}
void EVE1::mouseMoveEvent(QMouseEvent *event)
{
int X=event->x();
int Y=event->y();
int Z=scene->height()/2;
int W=scene->width()/2;
scene->addLine(Z,W,X,Y);
 
}

ScreenShot

EVE1.jpg

NOTE:MOVE YOUR MOUSE AROUND THE WIDGET, NOT ON THE WIDGET....

This page was last modified on 11 October 2012, at 04:17.
238 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved