The following code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCharts>
#include <QChartView>
#include <QBarSet>
#include <QBarSeries>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QBarSet *set0 = new QBarSet("People");
*set0 << 30 << 40 << 10 << 20 << 60 << 10;
QBarSeries *series = new QBarSeries();
series->append(set0);
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("Chart Example");
chart->setAnimationOptions(QChart::SeriesAnimations);
QStringList categories;
categories << "2023" << "2024" << "2025";
categories << "2026";
QBarCategoryAxis *axis = new QBarCategoryAxis();
axis->append(categories);
chart->createDefaultAxes();
chart->setAxisX(axis, series);
QChartView *chartView = new QChartView(chart);
chartView->setParent(ui->horizontalFrame);
}
makes the bar chart visible:

But when I move the bar chart code inside a pushbutton slot:
void MainWindow::on_pushButton_clicked()
{
QBarSet *set0 = new QBarSet("People");
*set0 << 30 << 40 << 10 << 20 << 60 << 10;
QBarSeries *series = new QBarSeries();
series->append(set0);
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("Chart Example");
chart->setAnimationOptions(QChart::SeriesAnimations);
QStringList categories;
categories << "2023" << "2024" << "2025";
categories << "2026";
QBarCategoryAxis *axis = new QBarCategoryAxis();
axis->append(categories);
chart->createDefaultAxes();
chart->setAxisX(axis, series);
QChartView *chartView = new QChartView(chart);
chartView->setParent(ui->horizontalFrame);
}
it does not become visible:

How do I make the bar chart visible when adding it in a slot?
The first code snippet does make the bar chart appear because it sets its parent before the
MainWindowinstance (the parent widget) is made visible because it's done in its constructor.The opposite is true for the second code snippet. The slot is called (when the button is clicked) after
showis called on theMainWindowinstance.Calling the parent's
showwill handle showing its child widgets, so any children added after that will not be made visible.Take a look at
QWidget::setVisblesource code.The solution to your problem is mentioned in
QWidget::setParent:Here is a very basic example using
QPushButtons, since the problem is not about bar charts: