0

我正在使用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 在要选择的项目上按 Enter 键:

 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 条记录的模型搜索,当我按 Enter 键时(QCompleter 确保我提交完整的 'cust_name')。QDebug() 输出 0。是否有另一种方法来获取id'cust_name'搜索查询匹配的'cust_name'

4

1 回答 1

1
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!

于 2017-10-14T11:37:00.193 回答