如何在窗口中与其他小部件一起显示QtChartView?

时间:2019-04-10 09:42:29

标签: c++ qt

我成功地遵循了以下youtube教程https://www.youtube.com/watch?v=MHn3ZTWcyXk&t=13m33s。我本质上是在尝试做与本教程完全相同的操作,但是这次是在一个更大的窗口中进行的,该窗口已经包含了一堆小部件和其他东西。我在类构造函数中调用以下函数。但是,这不会在ui-> graphview(即QChartView)中显示数据。

void RecordWidget::setupGraph(){

    QLineSeries *series = new QLineSeries();
    series->append(0, 16);
    series->append(1, 25);
    series->append(2, 24);
    series->append(3, 19);
    series->append(4, 33);
    series->append(5, 25);
    series->append(6, 34);

    // Create chart, add data, hide legend, and add axis
    QChart *chart = new QChart();
    chart->legend()->hide();
    chart->addSeries(series);
    chart->createDefaultAxes();

    // Customize the title font
    QFont font;
    font.setPixelSize(18);
    chart->setTitleFont(font);
    chart->setTitleBrush(QBrush(Qt::black));
    chart->setTitle("Barry Bonds HRs as Pirate");

    // Change the line color and weight
    QPen pen(QRgb(0x000000));
    pen.setWidth(5);
    series->setPen(pen);

    chart->setAnimationOptions(QChart::AllAnimations);

    // Change the x axis categories
    QCategoryAxis *axisX = new QCategoryAxis();
    axisX->append("1986",0);
    axisX->append("1987",1);
    axisX->append("1988",2);
    axisX->append("1989",3);
    axisX->append("1990",4);
    axisX->append("1991",5);
    axisX->append("1992",6);
    chart->setAxisX(axisX, series);

    // Used to display the chart
    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    ui->graphView = chartView;
    ui->graphView->show();
    ui->graphView->setVisible(true);
}

2 个答案:

答案 0 :(得分:0)

我会尝试:

ui->graphView->setChart(chart);

代替

QChartView *chartView = new QChartView(chart);
ui->graphView = chartView;

答案 1 :(得分:0)

分配ui->graphView

ui->graphView = chartView;已在布局中。您只需更改指针。相反,您必须首先将ui->graphView创建为QChartView