繁体   English   中英

如何向 QTreeView 添加项目?

[英]How to add items to a QTreeView?

下面的代码有什么问题? 它正在创建QTreeView ,但是,该视图不显示任何内容,只是一个细边框。

我还试图找到一种将小部件添加到特定行的方法。 我尝试使用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;
}

问题是您的model在 MainWindow ctor 的 scope 完成后被销毁。

// Create a model to hold the data
    QStandardItemModel model;

您可以将此 model 定义为成员变量(推荐)或像这样在堆上创建auto model = new QStandardItemModel; .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM