Skip to content

Instantly share code, notes, and snippets.

@Atsushi4
Created September 21, 2012 14:26
Show Gist options
  • Save Atsushi4/3761749 to your computer and use it in GitHub Desktop.
Save Atsushi4/3761749 to your computer and use it in GitHub Desktop.
Google MapのスクロールをQGraphicsViewで再現したい
#include <QtGui>
class GraphicsView : public QGraphicsView
{
Q_OBJECT
public:
GraphicsView(QWidget *parent = 0) : QGraphicsView(parent), mousePressed_(false)
{
init();
}
protected:
void mousePressEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton)
{
mousePressed_ = true;
timerId_ = startTimer(20);
prePosition_ = event->pos();
delta_ = QPoint();
ratio_ = 1;
}
QGraphicsView::mousePressEvent(event);
}
void mouseMoveEvent(QMouseEvent *event)
{
if (mousePressed_)
{
delta_ = event->pos() - prePosition_;
prePosition_ = event->pos();
}
QGraphicsView::mouseMoveEvent(event);
}
void mouseReleaseEvent(QMouseEvent *event)
{
if (mousePressed_)
mousePressed_ = false;
QGraphicsView::mouseReleaseEvent(event);
}
void timerEvent(QTimerEvent *event)
{
if (event->timerId() == timerId_ && !mousePressed_)
{
if (delta_ == QPoint() || ratio_ < 0.01)
{
killTimer(timerId_);
return;
}
scroll(horizontalScrollBar(), delta_.x() * ratio_);
scroll(verticalScrollBar(), delta_.y() * ratio_);
// ここを有効にすると減衰する
// ratio_ *= 0.95;
}
QGraphicsView::timerEvent(event);
}
private:
void init()
{
setAlignment(Qt::AlignCenter);
setDragMode(ScrollHandDrag);
}
void scroll(QScrollBar *bar, int point)
{
bar->setValue(bar->value() - point);
}
private:
bool mousePressed_;
QPoint prePosition_;
QPoint delta_;
int timerId_;
qreal ratio_;
};
void setScene(GraphicsView &view, int row, int width)
{
view.setScene(new QGraphicsScene(&view));
for (int i = 0; i < row; ++i)
{
int j = i * width;
view.scene()->addLine(j, 0, j, width * row);
view.scene()->addLine(0, j, width * row, j);
}
view.setSceneRect(0,0, row * width, row * width);
view.scale(2, 2);
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
GraphicsView view;
setScene(view, 100, 10);
view.show();
return app.exec();
}
#include "smoothzoom.moc"
@Atsushi4
Copy link
Author

ファイル名間違えてた。smoothmoveと書きたかった。mocもzoomになっちゃってるからもういい。(酔っぱらいですし

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment