C/C++ Qt 数据库与TreeView组件绑定详解

  #include "mainwindow.h"

  #include "ui_mainwindow.h"

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  // 定义数据模型指针

  QSqlQueryModel *qryModel; // 数据模型

  QItemSelectionModel *theSelection; // 选择模型

  QDataWidgetMapper *dataMapper; // 数据界面映射

  MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)

  {

  ui->setupUi(this);

  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

  db.setDatabaseName("http://www.jb51.net/article/lyshark.db");

  if (!db.open())

  {

  std::cout << db.lastError().text().toStdString()<< std::endl;

  return;

  }

  // 查询数据表中记录

  qryModel=new QSqlQueryModel(this);

  qryModel->setQuery("SELECT * FROM LyShark ORDER BY id");

  if (qryModel->lastError().isValid())

  {

  return;

  }

  // 设置TableView表头数据

  qryModel->setHeaderData(0,Qt::Horizontal,"ID");

  qryModel->setHeaderData(1,Qt::Horizontal,"Name");

  qryModel->setHeaderData(2,Qt::Horizontal,"Age");

  // 将数据绑定到模型上

  theSelection=new QItemSelectionModel(qryModel);

  ui->treeView->setModel(qryModel);

  ui->treeView->setSelectionModel(theSelection);

  ui->treeView->setSelectionBehavior(QAbstractItemView::SelectRows);

  }

  MainWindow::~MainWindow()

  {

  delete ui;

  }