我目前正在使用Qts Chart绘图工具。我现在有一个情节,我可以使用this示例提供的chartview类(进行小调整)放大和缩小。 我希望能够不仅缩放,而且还可以移动我的视图按下鼠标中键(在其他应用程序中使用很多,因此非常直观)。
我怎样才能在Qt中这样做?如何在按下鼠标中键的情况下鼠标移动时,如何检查是否按下并释放鼠标中键并在图中更改我的视图...
我确定有人之前已对此进行了编码,并且非常感谢一个小例子/帮助。
答案 0 :(得分:2)
您需要从QChartView
派生一个类并重载鼠标事件:
class ChartView: public QChartView
{
Q_OBJECT
public:
ChartView(Chart* chart, QWidget *parent = 0);
protected:
virtual void mousePressEvent(QMouseEvent *event) override;
virtual void mouseMoveEvent(QMouseEvent *event) override;
private:
QPointF m_lastMousePos;
};
ChartView::ChartView(Chart* chart, QWidget *parent)
: QChartView(chart, parent)
{
setDragMode(QGraphicsView::NoDrag);
this->setMouseTracking(true);
}
void ChartView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::MiddleButton)
{
QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor));
m_lastMousePos = event->pos();
event->accept();
}
QChartView::mousePressEvent(event);
}
void ChartView::mouseMoveEvent(QMouseEvent *event)
{
// pan the chart with a middle mouse drag
if (event->buttons() & Qt::MiddleButton)
{
QRectF bounds = QRectF(0,0,0,0);
for(auto series : this->chart()->series())
bounds.united(series->bounds())
auto dPos = this->chart()->mapToValue(event->pos()) - this->chart()->mapToValue(m_lastMousePos);
if (this->rubberBand() == QChartView::RectangleRubberBand)
this->chart()->zoom(bounds.translated(-dPos.x(), -dPos.y()));
else if (this->rubberBand() == QChartView::HorizontalRubberBand)
this->chart()->zoom(bounds.translated(-dPos.x(), 0));
else if (this->rubberBand() == QChartView::VerticalRubberBand)
this->chart()->zoom(bounds.translated(0, -dPos.y()));
m_lastMousePos = event->pos();
event->accept();
}
QChartView::mouseMoveEvent(event);
}
答案 1 :(得分:1)
我想提供一个更简单的Nicolas版本mouseMoveEvent()
:
void ChartView::mouseMoveEvent(QMouseEvent *event)
{
// pan the chart with a middle mouse drag
if (event->buttons() & Qt::MiddleButton)
{
auto dPos = event->pos() - lastMousePos_;
chart()->scroll(-dPos.x(), dPos.y());
lastMousePos_ = event->pos();
event->accept();
QApplication::restoreOverrideCursor();
}
QChartView::mouseMoveEvent(event);
}
此外,请务必包含QApplication::restoreOverrideCursor()
,以便在移动完成后光标恢复正常。