我目前正在使用 Qts Chart 绘图工具。我现在有一个绘图,我可以使用此示例提供的图表视图类进行放大和缩小(稍作调整)。我希望看到不仅可以缩放,还可以通过按下鼠标中键移动我的视图(这在其他应用程序中经常使用,因此非常直观)。
我怎样才能在 Qt 中做到这一点?如果鼠标在按下鼠标中键期间移动,我如何检查是否按下并释放鼠标中键并更改我在绘图中的视图...
我确定有人之前已经对此进行了编码,并且非常感谢一个小示例/帮助。
您需要从鼠标事件派生一个类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);
}
我想提供一个更简单的 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()
,以便在移动完成后光标恢复正常。