c++ - 在Qt中如何对QTreeWdiget上的节点和相对应的数据绑定?
PHP中文网
PHP中文网 2017-04-17 13:37:48
0
1
636

我目前的程序中需要一个QTreeWdiget来显示数据。

数据在代码里是一个结构体,里面有几百个变量(有基本类型,也有子结构体),结构体的每个变量的值已经通过memset赋值过。
现在我需要在QTreeWdiget显示出每个变量的名和值。
比如有一个结构是:

struct Child{
    long c;
    int d;
};
struct Node{
    char a;
    short b;
    Child child;
}

那么我希望在QTreeWdiget以树的形式展现出来,有什么简便的方法可以做到?

PHP中文网
PHP中文网

认证0级讲师

全部回覆(1)
大家讲道理

最簡單地,是使用 QtPropertyBrowser,可以參考官方的例子,我打包了一個 CMake 的版本:http://whudoc.qiniudn.com/2016/QtPropertyBrowser.7z

如果不想用這個函式庫,要自己來實現,要:

  1. 實作一個自己的 model,裡面需要有 datasetData 兩個函數,資料要放到一個特定的 role 裡,不要凌亂了;

  2. 給 TableView 設定 model(資料綁定在 model 裡);

  3. 為 TableView 設定 delegate(這是編輯資料的控制項);

簡單的說下 delegate。一個 delegate 通常需要繼承 QItemDelegate。一個 delegate 會拿到一個 widget(就是你的 treeView 的子 widget)的指針,然後創造一個 editor 以實現編輯功能,Editor 先從 widget 加載數據,然後編輯後再 setModelDate 把數據存回去。

// your model header file
class PointsModel : public QAbstractTableModel
{
public:
    PointsModel( QList<TextureNotation::TN_Pt> *pts, QObject *parent = 0 );
    int rowCount( const QModelIndex &parent ) const;
    int columnCount( const QModelIndex &parent ) const;
    QVariant data( const QModelIndex &index, int role ) const;
    bool setData( const QModelIndex &index, const QVariant &value, int role );
    QVariant headerData( int section, Qt::Orientation orientation, int role ) const;
    Qt::ItemFlags flags( const QModelIndex &index ) const;
    int numChangedPoints( ) { return changedPoints.size(); }
private:
    QList<TextureNotation::TN_Pt> *_pts;
    QSet<int> changedPoints;
};

// your delegate header file
class NotationPointDelegate : public QItemDelegate
{
    Q_OBJECT

public:
    NotationPointDelegate( QObject *parent = 0 );

    QWidget *createEditor( QWidget *parent, const QStyleOptionViewItem &option,
                           const QModelIndex &index ) const;
    void setEditorData( QWidget *editor, const QModelIndex &index ) const;
    void setModelData( QWidget *editor, QAbstractItemModel *model,
                       const QModelIndex &index ) const;
    void updateEditorGeometry( QWidget *editor,
                               const QStyleOptionViewItem &option, 
                               const QModelIndex &index ) const;
};

// your widget cpp file
doublespin = new NotationPointDelegate;
ui->tableView->setSortingEnabled( true );
ui->tableView->setItemDelegate( doublespin );

ui->tableView->setAlternatingRowColors( true );
ui->tableView->horizontalHeader()->setStretchLastSection( true );
ui->tableView->setEditTriggers( QAbstractItemView::DoubleClicked );
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!