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

标签 c++ qt user-interface

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

最佳答案

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

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

这将是 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
}

关于c++ - 使用 Qt 绘制抛物线或任何其他多项式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26093921/

相关文章:

c++ - Eigen 矩阵是否支持 vector 索引?

c++ - 如何从我的 HTTP 服务器向客户端发送图像?

c++ - 检查 C++ 指针是否有效(在 Objective-C(++) 中)

c++ - 启动时强制连接尚不可见的 QML 项的信号/槽

testing - 如何在没有远程桌面连接的情况下在 jenkins windows slave 上运行 GUI 测试?

c++ - 命名空间会使 C++ 中的原型(prototype)方法过时吗?

c++ - 如何为 QComboBox 的弹出菜单指定不同于框本身显示的字符串?

c++ - QML Camera 的无效/未定义媒体对象属性

ios - 使用约束为 3.5 和 4 英寸屏幕开发相同的 UI(仅限纵向模式)

c++ - Win API C++ 控制编辑必修