Форум программистов, компьютерный форум, киберфорум
C++ Qt
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.57/35: Рейтинг темы: голосов - 35, средняя оценка - 4.57
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54

Ошибка ASSERT failure in QVector<T>::operator[]: "index out of range"

29.07.2020, 13:24. Показов 8067. Ответов 43
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте, при попытке отладки кода возникает ошибка ASSERT failure in QVector<T>::operator[]: "index out of range".
Строчка, на которую ссылается программа в заголовочном файле qvector.h
C++ (Qt)
1
2
{ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::operator[]", "index out of range");
               return data()[i]; }
Файл main.cpp
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
#include "mainwindow.h"
 
using namespace std;
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
 
    return a.exec();
}
Файл mainwindow.h
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QApplication>
#include <iostream>
#include <math.h>
#include <string>
#include <fstream>
#include <vector>
 
#include <QMainWindow>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
private slots:  
    void makePlot();
 
    void on_pushButton_clicked();
 
private:
    Ui::MainWindow *ui;
};
 
#endif // MAINWINDOW_H
Файл mainwindow.cpp
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <fstream>
#include "qmath.h"
using namespace std;
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainWindow::makePlot();
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::makePlot()
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0 , a = 0, b = 0;
    QVector<double> x(101), y(101), y_pred(101); //set vectors indicating the number of numbers in them +1
    ifstream in("1.txt"); //path to the measurement file
        int i = 0;
        int n = 100; // number of pairs / experimental points
        while (!in.eof()) //fill arrays until an empty string appears
        {
            in >> x[i];
            in >> y[i];
            ++i;
        }
        in.close();
 
        for(int i = 0; i < 101; i++) //interim settlements
        {
            sumx += x[i];
        }
 
        for(int i = 0; i < 101; i++) //interim settlements
        {
            sumy += y[i];
        }
 
        for(int i = 0; i < 101; i++) //interim settlements
        {
            sumxy += x[i]*y[i];
        }
 
        for(int i = 0; i < 101; i++) //interim settlements
        {
            sumxx += x[i]*x[i];
        }
 
        for(int i = 0; i < 101; i++) //interim settlements
        {
            sumyy += y[i]*y[i];
        }
 
        a = (n*sumxy - sumx*sumy)/(n*sumxx - sumx*sumx); //we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(n*sumxx - sumx*sumx); //calculate b
        for(int i = 0; i < 101; i++) //fill the array of y values for the line
        {
            y_pred[i] = a*x[i] + b;
            QCPGraph* graph1 = ui->customPlot ->addGraph();
            graph1->setData(x, y_pred);
        }
 
        //ui->customPlot->clearGraphs();//If necessary, then clear all graphics
        ui->customPlot->addGraph(); //Add a chart
        ui->customPlot->graph(0)->setData(x, y);//We say that need to build a graph using arrays x and y
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
 
void MainWindow::on_pushButton_clicked()
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0 , a = 0, b = 0, r = 0, R = 0;
    QVector<double> x(100), y(100), y_pred(100); //set vectors indicating the number of numbers in them +1
    ifstream in("1.txt"); //path to the measurement file
        int i = 0;
        int n = 100; // number of pairs / experimental points
        while (!in.eof()) //fill arrays until an empty string appears
        {
            in >> x[i];
            in >> y[i];
            ++i;
        }
        in.close();
 
        for(int i = 0; i < 101; i++)//interim settlements
        {
            sumx += x[i];
        }
 
        for(int i = 0; i < 101; i++)//interim settlements
        {
            sumy += y[i];
        }
 
        for(int i = 0; i < 101; i++)//interim settlements
        {
            sumxy += x[i]*y[i];
        }
 
        for(int i = 0; i < 101; i++)//interim settlements
        {
            sumxx += x[i]*x[i];
        }
 
        for(int i = 0; i < 101; i++)//interim settlements
        {
            sumyy += y[i]*y[i];
        }
 
        a = (n*sumxy - sumx*sumy)/(n*sumxx - sumx*sumx);//we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(n*sumxx - sumx*sumx);//calculate b
 
        r = (n*sumxy - sumx*sumy)/qSqrt((n*sumxx - sumx*sumx)*(n*sumyy - sumy*sumy)); //calculate the correlation coefficient
 
        R = r*r;//calculate the square of the correlation coefficient
 
        ui->lineEdit->setText(QString::number(a));
        ui->lineEdit_2->setText(QString::number(b));
        ui->lineEdit_3->setText(QString::number(r));
        ui->lineEdit_4->setText(QString::number(R));
 
}
Программа, по идее, должна построить на графике точки из файла "1.txt" и аппроксимировать их прямой. Прежде она запускалась, но на самом графике также была ошибка - под аппроксимирующей прямой были какие-то другие совершенно непонятные прямые. Надеюсь на вашу поддержку.
0
Лучшие ответы (1)
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
29.07.2020, 13:24
Ответы с готовыми решениями:

Ошибка выполнения ASSERT failure in QVector<T>::at: "index out of range"
Взял ил документации qimage код создания объекта image ,попытался нарисовать его с помощью qpainter ,в итоге : ASSERT failure in...

Ошибка: ASSERT failure in QList::operator[]: "index out of range"
Добрый вечер. Есть дейтаграмма, из которой я хочу извлечь данные. Ставлю указатель на ту часть с которой хочу списать данные и на 12 строке...

ASSERT failure in QList<T>::operator[]: "index out of range", file C:\Qt\5.7\mingw53_32\include/QtCore/qlist.h, line 545
Добрый день. В программе где-то есть утечка памяти, но что-то никак не могу её найти и исправить. Вследствие чего выдаётся ошибка: ASSERT...

43
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
30.07.2020, 20:00  [ТС]
Студворк — интернет-сервис помощи студентам
Annemesski, ммм, приложение запускается без ошибок(то есть текстовый файл, как я понимаю, открывается), вот только на графике всего 1 точка (или все точки наложились друг на друга) с координатами (0; 0), а коэффициенты не вычисляются корректно (значение "nan").

Сам код:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qfile.h>
#include <QTextStream>
#include <QMessageBox>
#include "qmath.h"
#include <QString>
using namespace std;
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainWindow::makePlot();
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::makePlot()//здесь наносим на график точки из текстовго файла
{
    QVector<double> x, y;
    QFile f("2.txt");
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        QString tmp;
        while (stream.readLineInto(&tmp))
        {
            x.push_back(tmp.toDouble());
            stream.readLineInto(&tmp);
            y.push_back(tmp.toDouble());
    // остальные вычисления как в предыдущем варианте
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        //ui->customPlot->clearGraphs();
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
 
void MainWindow::on_pushButton_clicked()//здесь вычисляем коэффициенты и строим аппроксимирующую прямую
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0, a = 0, b = 0, r = 0, R = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        QString tmp;
        while (stream.readLineInto(&tmp))
        {
            x.push_back(tmp.toDouble());
            stream.readLineInto(&tmp);
            y.push_back(tmp.toDouble());
            sumx += x[x.size() - 1];
            sumy += y[y.size() - 1];
 
            sumxy += x[x.size() - 1] * y[y.size() - 1];
            sumxx += x[x.size() - 1] * x[x.size() - 1];
            sumyy += y[y.size() - 1] * y[y.size() - 1];
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        a = (x.size()*sumxy - sumx*sumy)/(x.size()*sumxx - sumx*sumx); //we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(x.size()*sumxx - sumx*sumx); //calculate b
 
        r = (x.size()*sumxy - sumx*sumy)/qSqrt((x.size()*sumxx - sumx*sumx)*(x.size()*sumyy - sumy*sumy)); //calculate the correlation coefficient
 
        R = r*r;//calculate the square of the correlation coefficient
 
        for(int i = 0; i < x.size(); i++) //fill the array of y values for the line
        {
            y_pred.push_back(a*x[i] + b);
        }
        QCPGraph* graph1 = ui->customPlot ->addGraph();
        graph1->setData(x, y_pred);
 
        ui->lineEdit->setText(QString::number(a));
        ui->lineEdit_2->setText(QString::number(b));
        ui->lineEdit_3->setText(QString::number(r));
        ui->lineEdit_4->setText(QString::number(R));
 
}
Добавлено через 3 минуты
Annemesski, я попробовал также поменять значения объявляемых переменных, и если им не задавать никаких значений, то ЧТО-ТО (коэффициенты a и b) считается.

Добавлено через 13 минут
Annemesski, может ли здесь быть дело в "теневой" сборке проекта в каком-то другом месте, из-за чего файл как-то криво читается ?
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
30.07.2020, 20:14
Цитата Сообщение от Fouly Посмотреть сообщение
может ли здесь быть дело в "теневой" сборке проекта в каком-то другом месте, из-за чего файл как-то криво читается ?
проверьте
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void MainWindow::makePlot()//здесь наносим на график точки из текстовго файла
{
    QVector<double> x, y;
    QFile f("2.txt");
    QString msg;
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        QString tmp;
        while (stream.readLineInto(&tmp))
        {
            x.push_back(tmp.toDouble());
            stream.readLineInto(&tmp);
            y.push_back(tmp.toDouble());
 
            sumx += x[x.size() - 1];
            sumy += y[y.size() - 1];
 
            sumxy += x[x.size() - 1] * y[y.size() - 1];
            sumxx += x[x.size() - 1] * x[x.size() - 1];
            sumyy += y[y.size() - 1] * y[y.size() - 1];
 
            msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        //ui->customPlot->clearGraphs();
 
 
    QMessageBox(QMessageBox::Information, "READED FROM FILE", msg).exec();
 
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
30.07.2020, 20:20  [ТС]
Annemesski, при запуске появляется окошко, в котором у X и Y одни нули.

Код:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qfile.h>
#include <QTextStream>
#include <QMessageBox>
#include "qmath.h"
#include <QString>
using namespace std;
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainWindow::makePlot();
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::makePlot()//здесь наносим на график точки из текстовго файла
{
    QVector<double> x, y;
        QFile f("2.txt");
        QString msg;
        if (f.open(QFile::ReadOnly))
        {
            QTextStream stream(&f);
            QString tmp;
            while (stream.readLineInto(&tmp))
            {
                x.push_back(tmp.toDouble());
                stream.readLineInto(&tmp);
                y.push_back(tmp.toDouble());
 
                msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
            }
            f.close();
        }
        else
        {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
            //ui->customPlot->clearGraphs();
 
 
        QMessageBox(QMessageBox::Information, "READED FROM FILE", msg).exec();
 
        //ui->customPlot->clearGraphs();
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
 
void MainWindow::on_pushButton_clicked()//здесь вычисляем коэффициенты и строим аппроксимирующую прямую
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0, a = 0, b = 0, r = 0, R = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        QString tmp;
        while (stream.readLineInto(&tmp))
        {
            x.push_back(tmp.toDouble());
            stream.readLineInto(&tmp);
            y.push_back(tmp.toDouble());
            sumx += x[x.size() - 1];
            sumy += y[y.size() - 1];
 
            sumxy += x[x.size() - 1] * y[y.size() - 1];
            sumxx += x[x.size() - 1] * x[x.size() - 1];
            sumyy += y[y.size() - 1] * y[y.size() - 1];
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        a = (x.size()*sumxy - sumx*sumy)/(x.size()*sumxx - sumx*sumx); //we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(x.size()*sumxx - sumx*sumx); //calculate b
 
        r = (x.size()*sumxy - sumx*sumy)/qSqrt((x.size()*sumxx - sumx*sumx)*(x.size()*sumyy - sumy*sumy)); //calculate the correlation coefficient
 
        R = r*r;//calculate the square of the correlation coefficient
 
        for(int i = 0; i < x.size(); i++) //fill the array of y values for the line
        {
            y_pred.push_back(a*x[i] + b);
        }
        QCPGraph* graph1 = ui->customPlot ->addGraph();
        graph1->setData(x, y_pred);
 
        ui->lineEdit->setText(QString::number(a));
        ui->lineEdit_2->setText(QString::number(b));
        ui->lineEdit_3->setText(QString::number(r));
        ui->lineEdit_4->setText(QString::number(R));
 
}
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
30.07.2020, 20:32
Fouly, значит файл читается не правильно, в какой он кодировке?

попробуйте так
C++ (Qt)
1
2
3
4
5
6
7
8
            while (stream.readLineInto(&tmp))
            {
                x.push_back(tmp.toLocal8Bit().toDouble());
                stream.readLineInto(&tmp);
                y.push_back(tmp.toLocal8Bit().toDouble());
 
                msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
            }
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
30.07.2020, 20:47  [ТС]
Annemesski, так тоже нули. Кодировка файла UTF-8.

Добавлено через 9 минут
Annemesski, то есть кодировка текстового файла UTF-8.
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
30.07.2020, 21:42
тогда
C++ (Qt)
1
2
3
4
5
6
7
8
            while (stream.readLineInto(&tmp))
            {
                x.push_back(QString::fromUtf8(tmp).toDouble());
                stream.readLineInto(&tmp);
                y.push_back(QString::fromUtf8(tmp).toDouble());
 
                msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
            }
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
30.07.2020, 22:06  [ТС]
Annemesski, в этом случае появляется ошибка "no matching function for call to 'fromUtf8'".

Сам код:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qfile.h>
#include <QTextStream>
#include <QMessageBox>
#include "qmath.h"
#include <QString>
using namespace std;
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainWindow::makePlot();
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::makePlot()//здесь наносим на график точки из текстовго файла
{
    QVector<double> x, y;
    QFile f("2.txt");
    QString msg;
     if (f.open(QFile::ReadOnly))
      {
            QTextStream stream(&f);
            QString tmp;
            while (stream.readLineInto(&tmp))
                        {
                            x.push_back(QString::fromUtf8(tmp).toDouble());
                            stream.readLineInto(&tmp);
                            y.push_back(QString::fromUtf8(tmp).toDouble());
             
                            msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
                        }
            f.close();
      }
        else
        {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        QMessageBox(QMessageBox::Information, "READED FROM FILE", msg).exec();
 
        //ui->customPlot->clearGraphs();
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
 
void MainWindow::on_pushButton_clicked()//здесь вычисляем коэффициенты и строим аппроксимирующую прямую
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0, a = 0, b = 0, r = 0, R = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        QString tmp;
        while (stream.readLineInto(&tmp))
        {
            x.push_back(tmp.toDouble());
            stream.readLineInto(&tmp);
            y.push_back(tmp.toDouble());
            sumx += x[x.size() - 1];
            sumy += y[y.size() - 1];
 
            sumxy += x[x.size() - 1] * y[y.size() - 1];
            sumxx += x[x.size() - 1] * x[x.size() - 1];
            sumyy += y[y.size() - 1] * y[y.size() - 1];
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        a = (x.size()*sumxy - sumx*sumy)/(x.size()*sumxx - sumx*sumx); //we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(x.size()*sumxx - sumx*sumx); //calculate b
 
        r = (x.size()*sumxy - sumx*sumy)/qSqrt((x.size()*sumxx - sumx*sumx)*(x.size()*sumyy - sumy*sumy)); //calculate the correlation coefficient
 
        R = r*r;//calculate the square of the correlation coefficient
 
        for(int i = 0; i < x.size(); i++) //fill the array of y values for the line
        {
            y_pred.push_back(a*x[i] + b);
        }
        QCPGraph* graph1 = ui->customPlot ->addGraph();
        graph1->setData(x, y_pred);
 
        ui->lineEdit->setText(QString::number(a));
        ui->lineEdit_2->setText(QString::number(b));
        ui->lineEdit_3->setText(QString::number(r));
        ui->lineEdit_4->setText(QString::number(R));
 
}
Добавлено через 17 минут
Annemesski, то есть ошибка появляется в строках

C++ (Qt)
1
2
3
4
5
6
7
8
while (stream.readLineInto(&tmp))
            {
                x.push_back(QString::fromUtf8(tmp).toDouble());//здесь ошибка no matching function for call to 'fromUtf8'
                stream.readLineInto(&tmp);
                y.push_back(QString::fromUtf8(tmp).toDouble());//здесь ошибка no matching function for call to 'fromUtf8'
 
                msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
            }
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
31.07.2020, 06:57
C++ (Qt)
1
x.push_back(QString::fromUtf8(tmp.c_str()).toDouble());
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
31.07.2020, 09:02  [ТС]
Annemesski, здесь ошибка no member named 'c_str' in 'QString' в строках

C++ (Qt)
1
2
3
4
5
6
7
8
 while (stream.readLineInto(&tmp))
              {
              x.push_back(QString::fromUtf8(tmp.c_str()).toDouble());//no member named 'c_str' in 'QString'
              stream.readLineInto(&tmp);
              y.push_back(QString::fromUtf8(tmp.c_str()).toDouble());//no member named 'c_str' in 'QString'
 
              msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
              }
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
31.07.2020, 09:43
Fouly, да, забыл, до c_str() надо вызывать toStdString(), так
C++ (Qt)
1
2
3
4
5
6
7
8
while (stream.readLineInto(&tmp))
              {
              x.push_back(QString::fromUtf8(tmp.toStdString().c_str()).toDouble());//no member named 'c_str' in 'QString'
              stream.readLineInto(&tmp);
              y.push_back(QString::fromUtf8(tmp.toStdString().c_str()).toDouble());//no member named 'c_str' in 'QString'
 
              msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
              }
по идее тот же эффект будет если сделать так
C++ (Qt)
1
2
3
4
5
6
7
8
while (stream.readLineInto(&tmp))
              {
              x.push_back(QString::fromUtf8(tmp.toLatin1()).toDouble());//no member named 'c_str' in 'QString'
              stream.readLineInto(&tmp);
              y.push_back(QString::fromUtf8(tmp.toLatin1()).toDouble());//no member named 'c_str' in 'QString'
 
              msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
              }
Хотя, наверное, сразу надо было предложить такой вариант:
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
    QTextStream stream(&f);
    stream.setCodec("UTF-8");
    QString tmp;
while (stream.readLineInto(&tmp))
{
    x.push_back(tmp.toDouble());//no member named 'c_str' in 'QString'
    stream.readLineInto(&tmp);
    y.push_back(tmp.toDouble());//no member named 'c_str' in 'QString'
 
    msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
}
Добавлено через 2 минуты
Если эти варианты не прокатят, прикрепите файл с числами к ответу, поглядим что там как.
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
31.07.2020, 10:21  [ТС]
Annemesski, к сожалению ничего не сработало из этих трех методов, хотя ошибок не выдает никаких.

Сам код

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qfile.h>
#include <QTextStream>
#include <QMessageBox>
#include "qmath.h"
#include <QString>
using namespace std;
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainWindow::makePlot();
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::makePlot()//здесь наносим на график точки из текстовго файла
{
    QVector<double> x, y;
    QFile f("2.txt");
    QString msg;
     if (f.open(QFile::ReadOnly))
      {
        QTextStream stream(&f);
        QString tmp;
          while (stream.readLineInto(&tmp))
              {
              x.push_back(QString::fromUtf8(tmp.toLatin1()).toDouble());
              stream.readLineInto(&tmp);
              y.push_back(QString::fromUtf8(tmp.toLatin1()).toDouble());
 
              msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
              }
            f.close();
      }
        else
        {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        QMessageBox(QMessageBox::Information, "READED FROM FILE", msg).exec();
 
        //ui->customPlot->clearGraphs();
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
 
void MainWindow::on_pushButton_clicked()//здесь вычисляем коэффициенты и строим аппроксимирующую прямую
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0, a = 0, b = 0, r = 0, R = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        QString tmp;
        while (stream.readLineInto(&tmp))
        {
            x.push_back(QString::fromUtf8(tmp.toLatin1()).toDouble());
            stream.readLineInto(&tmp);
            y.push_back(QString::fromUtf8(tmp.toLatin1()).toDouble());
            sumx += x[x.size() - 1];
            sumy += y[y.size() - 1];
 
            sumxy += x[x.size() - 1] * y[y.size() - 1];
            sumxx += x[x.size() - 1] * x[x.size() - 1];
            sumyy += y[y.size() - 1] * y[y.size() - 1];
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        a = (x.size()*sumxy - sumx*sumy)/(x.size()*sumxx - sumx*sumx); //we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(x.size()*sumxx - sumx*sumx); //calculate b
 
        r = (x.size()*sumxy - sumx*sumy)/qSqrt((x.size()*sumxx - sumx*sumx)*(x.size()*sumyy - sumy*sumy)); //calculate the correlation coefficient
 
        R = r*r;//calculate the square of the correlation coefficient
 
        for(int i = 0; i < x.size(); i++) //fill the array of y values for the line
        {
            y_pred.push_back(a*x[i] + b);
        }
        QCPGraph* graph1 = ui->customPlot ->addGraph();
        graph1->setData(x, y_pred);
 
        ui->lineEdit->setText(QString::number(a));
        ui->lineEdit_2->setText(QString::number(b));
        ui->lineEdit_3->setText(QString::number(r));
        ui->lineEdit_4->setText(QString::number(R));
 
}
А также .txt файл.
Вложения
Тип файла: txt 2.txt (59 байт, 1 просмотров)
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
31.07.2020, 10:56
Fouly, рукаладонь!!! Запутал я Вас, вот так должно сработать
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qfile.h>
#include <QTextStream>
#include <QMessageBox>
#include "qmath.h"
#include <QString>
using namespace std;
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainWindow::makePlot();
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::makePlot()//здесь наносим на график точки из текстовго файла
{
    QVector<double> x, y;
    QFile f("2.txt");
    QString msg;
     if (f.open(QFile::ReadOnly))
      {
        QTextStream stream(&f);
        double tmp;
          while (!(stream >> tmp).atEnd())
              {
              x.push_back(tmp);
              stream >> tmp;
              y.push_back(tmp);
 
              msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
              }
            f.close();
      }
        else
        {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        QMessageBox(QMessageBox::Information, "READED FROM FILE", msg).exec();
 
        //ui->customPlot->clearGraphs();
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
 
void MainWindow::on_pushButton_clicked()//здесь вычисляем коэффициенты и строим аппроксимирующую прямую
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0, a = 0, b = 0, r = 0, R = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        double tmp;
        while (!(stream >> tmp).atEnd())
        {
            x.push_back(tmp);
            stream >> tmp;
            y.push_back(tmp);
            sumx += x[x.size() - 1];
            sumy += y[y.size() - 1];
 
            sumxy += x[x.size() - 1] * y[y.size() - 1];
            sumxx += x[x.size() - 1] * x[x.size() - 1];
            sumyy += y[y.size() - 1] * y[y.size() - 1];
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        a = (x.size()*sumxy - sumx*sumy)/(x.size()*sumxx - sumx*sumx); //we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(x.size()*sumxx - sumx*sumx); //calculate b
 
        r = (x.size()*sumxy - sumx*sumy)/qSqrt((x.size()*sumxx - sumx*sumx)*(x.size()*sumyy - sumy*sumy)); //calculate the correlation coefficient
 
        R = r*r;//calculate the square of the correlation coefficient
 
        for(int i = 0; i < x.size(); i++) //fill the array of y values for the line
        {
            y_pred.push_back(a*x[i] + b);
        }
        QCPGraph* graph1 = ui->customPlot ->addGraph();
        graph1->setData(x, y_pred);
 
        ui->lineEdit->setText(QString::number(a));
        ui->lineEdit_2->setText(QString::number(b));
        ui->lineEdit_3->setText(QString::number(r));
        ui->lineEdit_4->setText(QString::number(R));
 
}
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
31.07.2020, 12:14  [ТС]
Annemesski, да, это действительно помогло! Но осталась одна проблема: хотя точки наносятся на график и коэффициенты вычисляются, но сам график прямой не строится.

Вот код:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qfile.h>
#include <QTextStream>
#include <QMessageBox>
#include "qmath.h"
#include <QString>
using namespace std;
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MainWindow::makePlot();
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::makePlot()//здесь наносим на график точки из текстового файла
{   double a = 0, b = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    QString msg;
     if (f.open(QFile::ReadOnly))
      {
        QTextStream stream(&f);
        double tmp;
          while (!(stream >> tmp).atEnd())
              {
              x.push_back(tmp);
              stream >> tmp;
              y.push_back(tmp);
 
              msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
              }
            f.close();
      }
        else
        {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        QMessageBox(QMessageBox::Information, "READED FROM FILE", msg).exec();
 
        for(int i = 0; i < x.size(); i++) //fill the array of y values for the line
        {
            y_pred.push_back(a*x[i] + b);
        }
        QCPGraph* graph1 = ui->customPlot ->addGraph();//ЗДЕСЬ СТРОИМ ГРАФИК ПРЯМОЙ
        graph1->setData(x, y_pred);//ЗДЕСЬ ПРЯМАЯ ОТРИСОВЫВАЕТСЯ ПО ЗАДАННЫМ ЗНАЧЕНИЯМ
 
        //ui->customPlot->clearGraphs();
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
}
 
void MainWindow::on_pushButton_clicked()//здесь вычисляем коэффициенты и строим аппроксимирующую прямую
{
    double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0, sumyy = 0, a = 0, b = 0, r = 0, R = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    if (f.open(QFile::ReadOnly))
    {
        QTextStream stream(&f);
        double tmp;
        while (!(stream >> tmp).atEnd())
        {
            x.push_back(tmp);
            stream >> tmp;
            y.push_back(tmp);
            sumx += x[x.size() - 1];
            sumy += y[y.size() - 1];
 
            sumxy += x[x.size() - 1] * y[y.size() - 1];
            sumxx += x[x.size() - 1] * x[x.size() - 1];
            sumyy += y[y.size() - 1] * y[y.size() - 1];
        }
        f.close();
    }
    else
    {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        a = (x.size()*sumxy - sumx*sumy)/(x.size()*sumxx - sumx*sumx); //we calculate the angular coefficient a of the approximating line
 
        b = (sumxx*sumy - sumx*sumxy)/(x.size()*sumxx - sumx*sumx); //calculate b
 
        r = (x.size()*sumxy - sumx*sumy)/qSqrt((x.size()*sumxx - sumx*sumx)*(x.size()*sumyy - sumy*sumy)); //calculate the correlation coefficient
 
        R = r*r;//calculate the square of the correlation coefficient
 
        ui->lineEdit->setText(QString::number(a));
        ui->lineEdit_2->setText(QString::number(b));
        ui->lineEdit_3->setText(QString::number(r));
        ui->lineEdit_4->setText(QString::number(R));
 
}
То есть по идее, в void MainWindow::makePlot() вместе с нанесением на график точек из файла должна также строиться и аппроксимирующая прямая, но ее просто нет и никаких ошибок при этом не всплывает.
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
31.07.2020, 12:31
По идее Вам надо убрать строки 51 и 52
C++ (Qt)
1
2
QCPGraph* graph1 = ui->customPlot ->addGraph();//ЗДЕСЬ СТРОИМ ГРАФИК ПРЯМОЙ
graph1->setData(x, y_pred);//ЗДЕСЬ ПРЯМАЯ ОТРИСОВЫВАЕТСЯ ПО ЗАДАННЫМ ЗНАЧЕНИЯМ
и сделать так
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ui->customPlot->addGraph();
ui->customPlot->graph(0)->setData(x, y);
ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
 
ui->customPlot->addGraph();
ui->customPlot->graph(1)->setData(x, y_pred);
ui->customPlot->graph(1)->setPen(QColor(255, 0, 0, 255));//set the color of the points
ui->customPlot->graph(1)->setLineStyle(QCPGraph::lsLine);//remove the lines
 
ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
ui->customPlot->yAxis->setLabel("y");
ui->customPlot->rescaleAxes();//scale the graph according to the data
ui->customPlot->replot();
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
31.07.2020, 12:59  [ТС]
Annemesski, так тоже не сработало. К тому же, не думаю, что отключение линий как у вас в сообщении в 10 строке имеет смысл для построения прямой. Вот void MainWindow::makePlot():

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void MainWindow::makePlot()//здесь наносим на график точки из текстовго файла
{   double a = 0, b = 0;
    QVector<double> x, y, y_pred;
    QFile f("2.txt");
    QString msg;
     if (f.open(QFile::ReadOnly))
      {
        QTextStream stream(&f);
        double tmp;
          while (!(stream >> tmp).atEnd())
              {
              x.push_back(tmp);
              stream >> tmp;
              y.push_back(tmp);
 
              msg.append("x = " + QString::number(x[x.size() - 1]) + "\ty = " + QString::number(y[y.size() -1]) + "\n");
              }
            f.close();
      }
        else
        {QMessageBox(QMessageBox::Warning, "ERROR", "Error: file not open").exec();}
 
        QMessageBox(QMessageBox::Information, "READED FROM FILE", msg).exec();
 
        for(int i = 0; i < x.size(); i++) //fill the array of y values for the line
        {
            y_pred.push_back(a*x[i] + b);
        }
 
        ui->customPlot->addGraph();
        ui->customPlot->graph(0)->setData(x, y);
        ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
        ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
        ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
 
        ui->customPlot->addGraph()->setData(x, y_pred);//ЗДЕСЬ Я ПОПЫТАЛСЯ ПОСТРОИТЬ ПО ПРИМЕРУ, КОТОРОМУ УЧИЛИ
        //ui->customPlot->graph()->setData(x, y_pred);
        //ui->customPlot->graph(1)->setPen(QColor(255, 0, 0, 255));//set the color of the points
        //ui->customPlot->graph(1)->setLineStyle(QCPGraph::lsLine);//remove the lines
 
        ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
        ui->customPlot->yAxis->setLabel("y");
        ui->customPlot->rescaleAxes();//scale the graph according to the data
        ui->customPlot->replot();
 
}
В коде я попытался построить этот график по примеру, который видел ранее ui->customPlot->addGraph()->setData(x, y_pred);, но это тоже не сработало.
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
31.07.2020, 13:31
Цитата Сообщение от Fouly Посмотреть сообщение
В коде я попытался построить этот график по примеру, который видел ранее
а я на Вас ориентировался... но должно быть что-то вроде
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ui->customPlot->addGraph();
ui->customPlot->graph(0)->setData(x, y);
ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
 
QCPCurve *aproxLine = new QCPCurve(ui->customPlot->xAxis, ui->customPlot->yAxis);
aproxLine->setData(x, y_pred);
ui->customPlot->addPlottable(aproxLine);
 
ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
ui->customPlot->yAxis->setLabel("y");
ui->customPlot->rescaleAxes();//scale the graph according to the data
ui->customPlot->replot();
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
31.07.2020, 13:34  [ТС]
Annemesski, простите если что, просто на занятиях и в документации Qt построение нескольких графиков в одном окне выглядело просто, а на деле позже пришлось искать различные сторонние решения подобной проблемы.
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
31.07.2020, 13:38
Fouly, ну так оно и не сложно тащем-то, вот разберите этот пример, должно стать понятнее.
0
0 / 0 / 0
Регистрация: 12.11.2018
Сообщений: 54
31.07.2020, 13:59  [ТС]
Annemesski, здесь появляется ошибка no member named 'addPlottable' in 'QCustomPlot'

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ui->customPlot->addGraph();
ui->customPlot->graph(0)->setData(x, y);
ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
 
QCPCurve *aproxLine = new QCPCurve(ui->customPlot->xAxis, ui->customPlot->yAxis);
aproxLine->setData(x, y_pred);
ui->customPlot->addPlottable(aproxLine);//ЗДЕСЬ ОШИБКА
 
ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
ui->customPlot->yAxis->setLabel("y");
ui->customPlot->rescaleAxes();//scale the graph according to the data
ui->customPlot->replot();
Добавлено через 20 минут
Annemesski, разве так должно быть ? no member named 'addPlottable' in 'QCustomPlot'
0
 Аватар для Annemesski
2691 / 1348 / 485
Регистрация: 08.11.2016
Сообщений: 3,739
31.07.2020, 14:19
Fouly, пистон автору того примера, действительно в QCustomPlot Class Reference такого метода нет, непонятно как автор составлял пример.

По идее должен работать предыдущий вариант, как здесь.

Давайте ка еще раз + повторим за примером не задумываясь
C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ui->customPlot->addGraph(ui-customPlot->xAxis, ui->customPlot->yAxis);
ui->customPlot->graph(0)->setData(x, y);
ui->customPlot->graph(0)->setPen(QColor(0, 0, 255, 255));//set the color of the points
ui->customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);//remove the lines
ui->customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 5));
ui->customPlot->graph(0)->setName("Dots graph");
 
ui->customPlot->addGraph();
ui->customPlot->graph(1)->setData(x, y_pred);
ui->customPlot->graph(1)->setPen(QColor(255, 0, 0, 255));//set the color of the points
ui->customPlot->graph(1)->setLineStyle(QCPGraph::lsLine);//sets the lines
ui->customPlot->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 5));
ui->customPlot->graph(1)->setName("Aprox line");
 
ui->customPlot->xAxis->setLabel("x");//We sign axes Ox and Oy
ui->customPlot->yAxis->setLabel("y");
ui->customPlot->rescaleAxes();//scale the graph according to the data
ui->customPlot->replot();
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
31.07.2020, 14:19

Ошибка ASSERT failure in QVector<T>::operator[]: "index out of range"
Выполняю простые операции, но получаю ошибку ASSERT failure in QVector&lt;T&gt;::operator: &quot;index out of range&quot; Ошибка проявляется...

Ошибка Assert Failure при запуске компилятора
При запуске компилятора возникает ошибка PascalABCNet.exe - Assert Failure Expression: Description: Infinite recursion during...

Runtime ошибка “ASSERT failure in QCoreApplication::sendEvent” при использовании QwtPlot
Есть простенький код, использующий QwtPlot в QQuickPaintedItem: /* qmlqwtplotter.h */ #include &lt;QQuickPaintedItem&gt; #include...

Ошибка cannot deference out of range deque operator
Все привет! Столкнулся со следующей ошибкой: cannot deference out of range deque operator Прошу помочь восстановить...

Assert failure in qlist
При дебаге вылетает ошибка


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
40
Ответ Создать тему
Новые блоги и статьи
Как у меня протекала болезнь
zorxor 27.08.2026
Здравствуйте, друзья! Эта запись блога предназначена именно для вас - для моих дорогих друзей, которые знали меня лично. Чтобы ответить на вопрос - а что же со мной произошло на самом деле? Я учился. . .
Нашел вот забавное видео о измерениях. Лучшее что я видел на эту тему
kumehtar 26.08.2026
ILETXiw9bMQ Основная суть и тезисы по измерениям: 0D (Нулевое измерение): точка, не имеющая длины, ширины, высоты или объема. Объект не может перемещаться в 0D. 1D (Первое измерение):. . .
[EasyBuilder Pro] Памятка по разработке для панелей Weintek
ФедосеевПавел 26.08.2026
Памятка по разработке для панелей Weintek ВВЕДЕНИЕ Ранее, при реализации проектов основное внимание уделял разработке управляющей программы для контроллера, а панели оператора доставалось время. . .
Модель по догадкам
anaschu 25.08.2026
Прошло две недели. Я уже рассказывал, как разговаривал с сотрудниками у сортировки и как понял, что главная ветка — не про приёмку, а про отбор. Но тогда я думал, что понял механику. На этой неделе я. . .
Запись в регистр сведений независимо от заполненности табличной части
Maks 25.08.2026
Реализация из решения ниже выполнена на нетиповом документе с несколькими табличными частями, разработанного в КА2. Задача: Обеспечить запись документа в регистр сведений независимо от. . .
Ноутбук Альфария
kumehtar 24.08.2026
Встретился тут в сети ноутбук Альфария, примарха Альфа-Легиона. Хотя возможно, это ноутбук Омегона, разумеется. Ну как вам?
Мастера простых решений
DevAlt 23.08.2026
В сишарп стэках winforms, да и wpf существует сложная система связывания источниках данных и элементов формы(текстовые поля и метки), опирается все это на технологию событий и мета. . .
Цена ошибки
DevAlt 23.08.2026
Человек я беспокойный и потому заинтересовался OCaml, в чате форсили функторы модулей как суперфичу. Пытаясь отдуплить концепт, наткнулся на тутор с простым примером. А главный принцип обучения от. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru