使用Qt绘制抛物线或任何其他多项式

using Qt to paint a parabola or any other polynomial

本文关键字:任何 其他 多项式 线或 Qt 绘制 使用      更新时间:2023-10-16

有没有办法使用Qt库来绘制抛物线或任何其他多项式?我试过使用QPainter,但没有这样的选择。感谢

如果你想使用QPainter,那么你应该使用QImage或QPixmap来显示或保存你的输出。

这是一个简单的代码,展示了如何在Qt小工具应用程序中完成它。

这将是MainWindow.h文件。

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QImage>
#include <QPainter>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    void drawMyFunction(qreal xMin,qreal xMax);
    qreal myFunction(qreal x);
    QImage * pic;
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

这将是您的MainWindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    drawMyFunction(-3,3);
}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::drawMyFunction(qreal xMin, qreal xMax)
{
    qreal step = (xMax - xMin) / 1000;
    QPainterPath painterPath;
    QSize picSize(300,300);
    for(qreal x = xMin ; x <= xMax ; x = x + step)
    {
        if(x == xMin)
        {
            painterPath.moveTo(x,myFunction(x));
        }
        else
        {
            painterPath.lineTo(x,myFunction(x));
        }
    }
    // Scaling and centering in the center of image
    qreal xScaling = picSize.width() / painterPath.boundingRect().width();
    qreal yScaling = picSize.height() / painterPath.boundingRect().height();
    qreal scale;
    if(xScaling > yScaling)
        scale = yScaling;
    else
        scale = xScaling;
    for(int i = 0 ; i < painterPath.elementCount() ; i++ )
    {
        painterPath.setElementPositionAt(i,painterPath.elementAt(i).x*scale +     picSize.width()/2,-painterPath.elementAt(i).y*scale + picSize.height()/2);
    }
    // Drawing to the image
    pic = new QImage(picSize,QImage::Format_RGB32);
    pic->fill(Qt::white);
    QPainter picPainter(pic);
    QPen myPen;
    myPen.setColor(Qt::black);
    myPen.setWidth(10);
    picPainter.drawPath(painterPath);
    ui->label->setPixmap(QPixmap::fromImage(*pic)); // label is an added label to the ui
    // you can also do this instead of just showing the picture
    // pic->save("myImage.bmp");
}
qreal MainWindow::myFunction(qreal x)
{
    return x*x; // write any function you want here
}

您尝试过QPainterPath吗?它具有QPainterPath::quadTo和QPainterPath::cubicTo成员函数,这些函数可能会有所帮助。

从多项式函数中计算离散点,并使用QPainter::drawLines绘制图形。

例如,y = x^2:

   float xmin = 0;
   float xmax = 2;
   float step = 0.1; // experiment with values
   QVector<QPointF> points;
   float x = xmin;
   while(x < xmax)
   {
       float y = x^x; //f(x)
       lines.push_back(QPointF(x,y));
       x+= step;
   }
   painter.drawLines(points);

因为qt坐标中的上角是(0,0)。计算y后,您需要对x和y进行几何平移。

相关文章: