QCustomPlot窗口缩放导致坐标轴刻度重叠
  JCsIkAITQy58 2023年11月02日 46 0

问题复现

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置鼠标拖拽图像和鼠标滚轮缩放图像
    ui->widget->setInteractions(QCP::iRangeDrag |QCP::iRangeZoom);

    //先添加一条曲线
    ui->widget->addGraph();
    //设置x轴刻度线的数据的格式,默认会有6位小数
    ui->widget->xAxis->setNumberFormat("f");
    //设置数据
    QVector<double> keyVector;
    QVector<double> valueVector;
    for(int i = 0; i < 5; i++)
    {
        keyVector.append(i);
        valueVector.append(2 * i + 3);
    }
    //将数据添加到曲线上
    ui->widget->graph(0)->setData(keyVector, valueVector);
    ui->widget->graph(0)->rescaleValueAxis();
    ui->widget->xAxis->setRange(0, 5);
    //重新绘制
    ui->widget->replot();
}

Widget::~Widget()
{
    delete ui;
}

问题效果展示

QCustomPlot窗口缩放导致坐标轴刻度重叠_QT QCustomPlot

可以看见因为窗体缩小了,而又必须保证x轴所有的刻度必须显示。所以导致了刻度重叠的现象。解决办法是。窗体缩小视图不缩小,即不要求视图显示所有的刻度。当窗体放大时,视图也跟着放大。

解决代码

让我们先看一看 QCustomPlot 的  ResizeEvent做了什么

/*! \internal
  
  Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
  of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
*/
void QCustomPlot::resizeEvent(QResizeEvent *event)
{
  Q_UNUSED(event)
  // resize and repaint the buffer:
  setViewport(rect());
  replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
}

可以看到只是将Viewport 设置位当前窗口的大小。联合上面的现象我们可以得出 视图大小是一个矩形。无论视图有多大或者多小,QCustomPlot都会将整个图像展示到这个视图大小中(即使出现重叠的现象)  当视图的矩形较大,而窗体的矩形较小。那么就会出现下图显示的效果。图像没有被缩放,但是由于窗体矩形变小。所以只能观察到部分图像。

#include "MyCustomPlot.h"

MyCustomPlot::MyCustomPlot(QWidget *parent) : QCustomPlot(parent),initViewRect_(QRect())
{

}

void MyCustomPlot::setInitViewRect(const QRect &rect)
{
    initViewRect_ = rect;
}

void MyCustomPlot::resizeEvent(QResizeEvent *event)
{
    if(!initViewRect_.isNull())
    {
        if(rect().width() < initViewRect_.width() || rect().height() < initViewRect_.height())
        {
            QWidget::resizeEvent(event);
            replot();
            return;
        }
        else
        {
            return QCustomPlot::resizeEvent(event);
        }
    }
    return QCustomPlot::resizeEvent(event);
}

解决效果

QCustomPlot窗口缩放导致坐标轴刻度重叠_QT QCustomPlot_02

结尾

51CTO博客小萌新一枚,欢迎大家在评论区交流

代码下载地址 customPlotTest

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论