【问题标题】:How to make a GUI that plots user-entered function(x)?如何制作一个绘制用户输入函数(x)的图形用户界面?
【发布时间】:2022-01-24 00:22:35
【问题描述】:

我正在开发一个程序,它从用户那里获取 x 的函数,它还获取 x 的最小值和最大值,然后程序必须绘制这个函数。 例如:

用户输入的函数(x)是:x^2+2x-1
x 的最大值为:3
x 的最小值为:-3

现在 GUI 必须显示 (如果输入的函数没有错误,否则错误将显示给用户)类似于此图像的内容:

输入的函数也可能有点复杂,例如(sin(x), cos(2*x+1), etc..)

我正在尝试使用 C++ 和 QT 来完成这项工作,所以任何建议如何使用 QT 制作程序的绘图部分,或者如果有人知道更好的推荐而不是 QT 与 C++ 一起工作并且可以完成这项工作。
提前致谢。

【问题讨论】:

  • 看看 QCustomPlot 库。它由一个.cpp 和一个.h 文件组成。使用方便。不过,您仍然需要进行数学运算,它只会帮助您绘制一组 x、y 坐标。
  • 好的,我去查一下,谢谢

标签: c++ qt user-interface


【解决方案1】:

您将需要一个解释数学表达式的库(即:muparser)。在代码中,我做了自己的数学运算,但您将使用库来做。考虑到你管理了所有这些;使用 QCustomPlot,您可以绘制图表。
下面是一个示例,让您了解如何使用 QCustomPlot:

/** I copy pasted the code from one of my projects, please ignore function & class namings
 */
/** somewhere in your window constructor, create a QCustomPlot
 * widget and add graphs to your QCustomPlot widget.
 * example: ui->plt_freq_domain->addGraph();
 */

void ControllerMain::plot_frequency_domain()
{
    QVector <double> vec_keys(1024), vec_values(1024);
    //fill x axis values with incrementing numbers from 0 to 1024 (or any other number you want)
    // let's say your function is y = x^2 and calculate all y values and store them in vec_values
    for(int i = 0; i < vec_keys.size(); i++)
    {
        vec_values[i] = std::pow(vec_keys[i], 2);
    }
    
    // we fill keys with continuous integers [0,1023] so our graph spans along x-axis
    std::iota(vec_keys.begin(), vec_keys.end(), 0); 

    ui->plt_freq_domain->graph(0)->setData(vec_keys, vec_values, true);
    ui->plt_freq_domain->graph(0)->setPen(QPen(QColor(245, 197, 66)));

    ui->plt_freq_domain->yAxis->setLabel("A/m"); // change it with your unit or just keep empty
    ui->plt_freq_domain->yAxis->setRange(*std::min_element(vec_values.begin(), vec_values.end()), 
                                                            *std::max_element(vec_values.begin(), vec_values.end()));

    ui->plt_freq_domain->xAxis->setLabel("f"); // change it with your unit or just keep empty
    ui->plt_freq_domain->xAxis->setRange(vec_keys.constFirst(), vec_keys.constLast());

    ui->plt_freq_domain->replot();
}

【讨论】:

  • 非常感谢您的帮助
猜你喜欢
  • 2010-09-05
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多