我一直在问,并在某个地方找到了一些有用的信息,并测试写了这个:
tgs.cpp
:
#include <QtGui>
#include "tgs.h"
#define _alto 300
#define _ancho 700
#include <QGraphicsSceneMouseEvent>
TGs::TGs(QObject *parent)
:QGraphicsScene(parent)
{ // Constructor of Scene
this->over = false;
}
void TGs::drawBackground(QPainter *painter, const QRectF &rect)
{
#define adjy 30
#define adjx 30
int j = 0;
int alto = 0;
QPen pen;
pen.setWidth(1);
pen.setBrush(Qt::lightGray);
painter->setPen(pen);
painter->drawText(-225, 10, this->str);
alto = _alto; // 50 + 2
for(int i = 0; i < alto; ++i)
{
j = i * adjy - 17;
painter->drawLine(QPoint(-210, j), QPoint(_ancho, j));
}
for(int i = 0; i < 300; ++i)
{
j = i * adjx - 210;
painter->drawLine(QPoint(j, 0), QPoint(j, _ancho * 2));
}
}
void TGs::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
QString string = QString("%1, %2")
.arg(mouseEvent->scenePos().x())
.arg(mouseEvent->scenePos().y()); // Update the cursor position text
this->str = string;
this->update();
}
void TGs::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
this->update();
}
void TGs::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
this->update();
}
tgs.h
:
#ifndef TGS_H
#define TGS_H
#include <QObject>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsTextItem>
QT_BEGIN_NAMESPACE
class QGraphicsSceneMouseEvent;
class QMenu;
class QPointF;
class QGraphicsLineItem;
class QFont;
class QGraphicsTextItem;
class QColor;
QT_END_NAMESPACE
class TGs : public QGraphicsScene
{
public:
TGs(QObject *parent = 0);
public slots:
void drawBackground(QPainter *painter, const QRectF &rect);
void mouseMoveEvent(QGraphicsSceneMouseEvent * mouseEvent);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
bool over;
QString str;
QGraphicsTextItem cursor;
};
#endif // TGS_H