QPainter/QTransform zoom-to-point
-
Hello, I already spent lot of hours and still can't figure out how to do a CAD-like zoom-to-point with mouse wheel and translation using drag-and-drop on a drawing drawed by QPainter. My last code looks like this:
@Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->resize(500,500);t.translate( 0, 0); t.scale( 1, 1 ); scale = 1; originx = 0; originy = 0; mouseLast.setX(-1);
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter p(this);p.fillRect(event->rect(), Qt::black); p.setTransform(t); p.setPen(Qt::blue); p.drawLine(100,100, 400, 400);
}
void Widget::wheelEvent(QWheelEvent *event)
{
if (event->orientation() == Qt::Vertical)
{
//qDebug() << "event x:" << event->x();float wheel = event->delta()/120;//n or -n float zoom = pow(1.0 + abs(wheel)/4.0 , wheel > 0 ? 1 : -1); QPointF pt = t.map(QPointF(event->x(), event->y())); scale*= zoom; qDebug() << "zoom :" << zoom << " scale:" << scale; t.reset(); t.translate( pt.x()-originx, pt.y()-originy); t.scale(scale, scale); originx*= zoom; originy*= zoom; t.translate( -pt.x()+originx, -pt.y()+originy); repaint(); } event->accept();
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if(mouseLast.x() != -1)
{
t.translate((event->x() - mouseLast.x())/scale, (event->y() - mouseLast.y())/scale);
originx += (event->x() - mouseLast.x())/scale;
originy += (event->y() - mouseLast.y())/scale;
}mouseLast.setX(event->x()); mouseLast.setY(event->y()); repaint(); event->accept();
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
mouseLast.setX(-1);
event->accept();
}Widget::~Widget()
{
delete ui;
}@It works pretty good when I'm just zooming, but when I try to move the line and then zoom to it, then it zooms to a bad point. The code that does the moving looks pretty weird, becouse after I failed to figure out the right way I started trying almost everything.
Can somebody help me?
(Example Creator project here: "http://luzny.cz/uploads/qtransformtest.zip":http://luzny.cz/uploads/qtransformtest.zip )