簡體   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