当前位置:嗨网首页>书籍在线阅读

14-记录排序

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

11.2.8 记录排序

QSqlTableModel的setSort()函数设置数据表根据某个字段按照升序或降序排列,实际上就是设置了SQL语句里的ORDER BY子句。

在打开数据库时,已经调用getFieldNames()函数将数据表的所有字段名添加到界面上的comboFields下拉列表框了。“排序字段”下拉列表框、“升序”和“降序”两个RadioButton的相应操作的槽函数实现按选择字段排序。

void MainWindow::on_comboFields_currentIndexChanged(int index)
{//选择字段进行排序
   if (ui->radioBtnAscend->isChecked())
      tabModel->setSort(index,Qt::AscendingOrder);
   else
      tabModel->setSort(index,Qt::DescendingOrder);
   tabModel->select();
}
void MainWindow::on_radioBtnAscend_clicked()
{//升序
   tabModel->setSort(ui->comboFields->currentIndex(),Qt::AscendingOrder);
   tabModel->select();
}
void MainWindow::on_radioBtnDescend_clicked()
{//降序
   tabModel->setSort(ui->comboFields->currentIndex(),Qt::DescendingOrder);
   tabModel->select();
}

在调用setSort()函数设置排序规则后,需要调用QSqlTableModel::select()重新读取数据表的数据才会使排序规则生效。