我试图创建一个程序,它从外部文件C:/Repo/GraphTestData.txt
中获取输入。
这发生在我的main.cpp
文件中,在那里它被解析成两个双QVector
s x
和y
。然后,我将它们外部导出到共享头data.h
,在那里它在另一个名为networkplot.cpp
的文件中被访问。在这里,我使用QCustomPlot
将数据绘制到图形上。然而,控制台显示data.h
没有被任何一个cpp文件直接使用。我该如何解决这个问题?
data.h
#ifndef DATA_H
#define DATA_H
#include <QVector>
extern QVector<double> x;
extern QVector<double> y;
#endif // DATA_H
网络图.h
#ifndef NETWORKPLOT_H
#define NETWORKPLOT_H
#include <QMainWindow>
#include <QVector>
QT_BEGIN_NAMESPACE
namespace Ui { class networkplot; }
QT_END_NAMESPACE
class networkplot : public QMainWindow
{
Q_OBJECT
public:
networkplot(QWidget *parent = nullptr);
~networkplot();
private:
Ui::networkplot *ui;
};
#endif // NETWORKPLOT_H
网络图.cpp
#include "networkplot.h"
#include "ui_networkplot.h"
#include <QDebug>
#include "data.h"
networkplot::networkplot(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::networkplot)
{
ui->setupUi(this);
extern QVector<double> x, y;
/*QVector<double> x(100),y(100);
for(int i=0;i<100;i++)
{
x[i] = i/50.0 - 1; // x goes from -1 to 1
y[i] = x[i]*x[i]; // quadratic function
}*/
ui->customplot->addGraph();
ui->customplot->graph(0)->setScatterStyle(QCPScatterStyle::ssDot);
ui->customplot->graph()->setLineStyle(QCPGraph::lsLine);
ui->customplot->xAxis->setLabel("X");
ui->customplot->yAxis->setLabel("Y");
ui->customplot->yAxis->setRange(-6000,100);
ui->customplot->yAxis->setRange(-6000,8000);
ui->customplot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
ui->customplot->graph(0)->setData(x,y);
ui->customplot->rescaleAxes();
ui->customplot->replot();
ui->customplot->update();
}
networkplot::~networkplot()
{
delete ui;
}
main.cpp
#include "networkplot.h"
#include <QApplication>
#include <QFile>
#include <QTextStream>
#include <QVector>
#include <QDebug>
#include "data.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// File path
QString filePath = "C:/Repo/GraphTestData.txt";
// Vectors to store data
QVector<double> x;
QVector<double> y;
// Open the file
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Error opening file:" << file.errorString();
return -1;
}
// Read the file line by line
QTextStream in(&file);
while (!in.atEnd()) {
// Read each line
QString line = in.readLine();
// Split the line into two doubles
QStringList parts = line.split(" ");
if (parts.size() == 2) {
bool conversionX, conversionY;
double numberX = parts[0].toDouble(&conversionX);
double numberY = parts[1].toDouble(&conversionY);
// Check if conversion was successful
if (conversionX && conversionY) {
// Append to vectors
x.append(numberX);
y.append(numberY);
} else {
qDebug() << "Error converting line to numbers:" << line;
}
} else {
qDebug() << "Invalid line format:" << line;
}
}
// Close the file
file.close();
// Print the content of vectors
qDebug() << "Vector x:" << x;
qDebug() << "Vector y:" << y;
networkplot w;
w.show();
return a.exec();
}
获取错误:
1条答案
按热度按时间icomxhvb1#
你应该在你的类之外定义你的全局变量,而不是在(类成员)之内。