PDA

View Full Version : Display cursor position in QGraphicsView



dbrmik
2nd April 2009, 12:14
Hi

I need a bit of help displaying the cursor position of a pixel in a pixmap (4k x 1k pixels) using QGraphicsView . I have subclassed QGraphicsView




class viewWidget : public QGraphicsView
{
Q_OBJECT;
public:
viewWidget(QWidget* parent =0);
virtual ~ viewWidget();

void paintEvent(QPaintEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);

signals:
void grabPosition(const QPoint);

private:
QPoint p;
QString posString;
float xScale;
float yScale;
};





viewWidget::viewWidget(QWidget* parent )
:QGraphicsView(parent),
xScale(1.0),
yScale(1.0)
{
setMouseTracking(true);
}

viewWidget::~viewWidget(){};

void
viewWidget::paintEvent(QPaintEvent* event)
{
QGraphicsView::paintEvent(event);
QPainter paint(this);
paint.setPen(QColor(Qt::yellow));
paint.drawText(p,posString);
}

void
viewWidget::mouseMoveEvent(QMouseEvent* event)
{
if (scene()==NULL)
return;

p=mapToScene(event->pos());
posString = QString::number( (p.x() ) + "," + QString::number( p.y() );

cout << qPrintable(posString) << endl;
update();
}


I create a QGraphicsScene from a pixmap and add it to the view as shown



view=new viewWidget(this); //Create a view widget
scene=new QGraphicsScene(view);
scene->addPixmap(QPixmap::fromImage(*image));
view->setScene(scene);
view->show();


However the pixel position is not shown on the view, I get an error from the debugger

warning: QPainter::setPen: Painter not active

What am I doing wrong?

Thanks

dbrmik
2nd April 2009, 15:06
Hi

Do I need to subclass QGraphicsScene and re-implement the painttEvent and mouseMoveEvent ? I can display the pixel positon in the status bar, bit I would like it attached the the cursor.

Thanks