What's wrong with the code below? It's creating the QTreeView
, however, the view doesn't display anything, just a thin border.
I was also trying to find a way to add a widget into a specific row. I tried with a QPushButton
.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QGridLayout* layout = new QGridLayout();
ui.centralWidget->setLayout(layout);
QTreeView* treeView = new QTreeView(this);
treeView->setStyleSheet(R"(
QTreeView {
background-color: transparent;
}
)");
// Create a model to hold the data
QStandardItemModel model;
// Set the model to the tree view
treeView->setModel(&model);
// Add columns to the model
QStandardItem* column1 = new QStandardItem("Column 1");
column1->setBackground(QBrush(Qt::red));
model.setHorizontalHeaderItem(0, column1);
model.setHorizontalHeaderItem(1, new QStandardItem("Column 2"));
// Add data to the model
for (int i = 0; i < 5; i ) {
// Create a new row
QList<QStandardItem*> row;
// Create items for the row
QStandardItem* item1 = new QStandardItem("Data " QString::number(i));
QStandardItem* item2 = new QStandardItem("More data " QString::number(i));
// Add the items to the row
row << item1 << item2;
// Create a push button
QPushButton* button = new QPushButton("Button " QString::number(i));
// Add the button to the first column
item1->setData(QVariant::fromValue(static_cast<void*>(button)));
// Add the row to the model
model.appendRow(row);
}
layout->addWidget(treeView);
treeView->show();
return;
}
CodePudding user response:
The problem is your model
destroyed after MainWindow ctor's scope finishes.
// Create a model to hold the data
QStandardItemModel model;
You can define this model as member variable (recommended) or create on heap like this auto model = new QStandardItemModel;
.