Search code examples
qtqtabwidget

add chart in QTabWidget


I want to read data form text file and add chart of the numbers in tabWidget (tab1) but when showing , new widget was open , how can I fix this?

void mainWindow::readfile(){

    QFile config(":/new/prefix1/3.txt");
    config.open(QIODevice::ReadOnly);
    if(config.isOpen()){
        QTextStream stream(&config);
        while (!stream.atEnd()){
         line = stream.readLine().split('\t');
        //qDebug()<<line;
        bool allOk(true);
        bool ok;
        for (int x = 0; x <= line.count()-1 && allOk; x++) {
        val.append(line.at(x).toInt(&ok));
        allOk &= ok;
            }
        }
}
    else
        qDebug()<<"not opened";
     ui->stackedWidget->setCurrentIndex(8);
     on_ecg_destroyed();
}

void mainWindow::on_ecg_destroyed()
{
    QLineSeries *series = new QLineSeries();
        for(int y=0;y<288;y++)
            series->append(y,val[y]);

    QChart *chart = new QChart();
    chart->legend()->hide();
    chart->addSeries(series);
    chart->createDefaultAxes();
    chart->setTitle("line chart");
     QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
    setCentralWidget(chartView);
    resize(400, 300);
    show();
}

I use QStackWidget to define the pages, and in one of them(pages), I use QTabWidget with four tabs and I want to create a graph in tab 1. QTabWidget is located in QStackWidget index 8, After reading the file, show the chart on page 8 in tab1.


Solution

  • In your code you need to add chartview to correct Tab of QTabWidget , you can create a layout, add chartview to the created layout, then set tab1 layout to that new layout:

    QChart *chart = new QChart();
    chart->legend()->hide();
    chart->addSeries(series);
    chart->createDefaultAxes();
    chart->setTitle("line chart");
    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
    // create layout
    QGridLayout layout;
    layout.addWidget(chartView);
    this->ui->tab1->setLayout(&layout);
    // position view to chartview
    this->ui->stackedWidget->setCurrentIndex(8);
    this->ui->tabWidget->setCurrentIndex(this->ui->tabWidget->indexOf(this->ui->tab1));