获取id字段作为QSqlTableModel中记录的int

时间:2017-10-14 10:44:12

标签: c++ qt qtsql qsqltablemodel qcompleter

我正在使用QSqlTableModel *modelcompleter,然后使用QCompleter将数据加载到qLineEdit *search

    connect(ui->btnSearch, SIGNAL(clicked()), SLOT(search()));
    modelcompleter->setTable("cust");
    modelcompleter->setEditStrategy(QSqlTableModel::OnManualSubmit);
    modelcompleter->select();
    QCompleter *searchCompleter = new QCompleter(modelcompleter);
    searchCompleter->setCompletionColumn(1);
    searchCompleter->setCaseSensitivity(Qt::CaseInsensitive);
    ui->search->setCompleter(searchCompleter);

我正在使用qlineEdit来输入我想要选择的项目:

 connect(ui->search, SIGNAL(returnPressed()), SLOT(search()));

功能

void search(){
cust_name = ui->search->text();
    modelsearch->setTable("cust");
    modelsearch->setEditStrategy(QSqlTableModel::OnManualSubmit);
    modelsearch->setFilter(QString("cust_name like '%%1%'").arg(cust_name));
    modelsearch->select();
    qDebug() << modelsearch->record(0).value("id").toInt(); }

我不明白为什么,但是当我点击输入时,目前只设置为1记录的模型搜索(QCompleter确保我提交完整的&#39; cust_name&#39;)。 QDebug()输出0.是否有另一种方法可以获得与搜索查询id匹配的'cust_name' 'cust_name'

1 个答案:

答案 0 :(得分:0)

qDebug() << modelsearch->record(0).value("id").toInt();

而不是这个。我用了

QSqlQueryModel *query = new QSqlQueryModel;
query->setQuery(QString("SELECT id from cust WHERE cust_name like '%%1%'").arg(cust_name));
qDebug() << query->record(0).value("id").toInt();

现在正在获取记录的ID!