5 Qter豆
如果createIndex(0,0,0) 则出现错误 call of overloaded 'createIndex(int&, int&, int)' is ambiguous return createIndex(row, column, 0); 第三个参数 改为“createIndex ( row , column , Q_NULLPTR ) ”就没问题,如果第三个参数为其他数字又没问题。
我是用5.7版本。
代码如下:
-------TreeModel.h----------------------------- #ifndef TREEMODEL_H#define TREEMODEL_H #include <QAbstractItemModel>
class TreeModel : public QAbstractItemModel { Q_OBJECT public : TreeModel (); int rowCount ( const QModelIndex & parent ) const ; int columnCount ( const QModelIndex & parent ) const ; QModelIndex index ( int row, int column, const QModelIndex & parent = QModelIndex () ) const ; QModelIndex parent ( const QModelIndex & index ) const ; QVariant data ( const QModelIndex & index, int role ) const ; QVariant headerData ( int section, Qt :: Orientation orientation, int role) const ;
private : enum { N = 15 }; int numbers [ N ]; };
#endif // TREEMODEL_H -------------------treemodel.cpp-------------------------#include "treemodel.h"
TreeModel :: TreeModel () { int values [ N ]={ 36 , 10 , 26 , 3 , 7 , 11 , 15 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }; for ( int i = 0 ; i < N ; i ++) numbers [ i = values [ i ]; }
int TreeModel :: rowCount ( const QModelIndex & parent ) const { if ( ! parent . isValid () ) return 1 ; if ( parent . internalId () < N / 2 ) return 2 ; return 0 ; }
int TreeModel :: columnCount ( const QModelIndex & parent ) const { return 1 ; }
QModelIndex TreeModel :: index ( int row , int column , const QModelIndex & parent ) const { if ( ! parent . isValid () ) return createIndex ( row , column , 0 ); // return createIndex(row, column, Q_NULLPTR);
int parent_idx = parent . internalId (); int idx = parent_idx * 2 + ( row + 1 ); return createIndex ( row , column , idx ); }
QModelIndex TreeModel :: parent ( const QModelIndex & index ) const { if ( index . internalId () == 0 ) return QModelIndex (); int parent_idx = ( index . internalId () - 1 )/ 2 ; return createIndex ( ( parent_idx + 1 ) % 2 , 0 , parent_idx ); }
QVariant TreeModel :: data ( const QModelIndex & index , int role ) const { switch ( role ) { case Qt :: DisplayRole : int value = numbers [ index . internalId () ]; return QVariant ( value ); } return QVariant (); }
QVariant TreeModel :: headerData ( int section , Qt :: Orientation orientation , int role ) const { if ( role == Qt :: DisplayRole && section == 0 && orientation == Qt :: Horizontal ) return QString ( "Full Binary Tree" ); return QVariant (); } -------------------main.cpp-----------------------------#include "treemodel.h" #include <QApplication> #include <QTreeView>
int main ( int argc , char * argv []) { QApplication app ( argc , argv ); TreeModel treeModel ;
QTreeView treeView ( 0 ); treeView . setModel ( & treeModel ); treeView . show (); return app . exec (); }
-----------------Change_header.pro--------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = change header
TEMPLATE = app
SOURCES += main.cpp\
treemodel.cpp
HEADERS += treemodel.h
我来回答