首页 > 在Qt中如何对QTreeWdiget上的节点和相对应的数据绑定?

在Qt中如何对QTreeWdiget上的节点和相对应的数据绑定?

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

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

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

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


最简单地,是使用 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 );
【热门文章】
【热门文章】