Is it possible to get primary key of selected text from QCompleter

1.5k Views Asked by At

I am using a QCompleter on line edit to get some text. The completer functionality is as such working fine.

The QCompleter is fetching data from Sql Table.

completer = new QCompleter(this);
model = new QSqlRelationalTableModel(this, db);
model->setTable("product"); 
model->select();
completer->setModel(model);
completer->setCompletionColumn(1);                 // points to "name" in product table
ui->line_edit->setCompleter(completer);

now on line_edit_returnPressed(), I am able to get the selected text. Is it further possible to get the primary key / row index in Sql Table for the currect selection made from "QCompleter" ?

I see that ui->line_edit->completer()->currentRow(); always return 0.

I am just trying to save one SQL query thats all.

1

There are 1 best solutions below

0
On BEST ANSWER

I have to acknowledge @Pavel Strakhov comments, thanks. Had it been put up as answer, I would have accepted it.

The whole time I was using QCompleter::currentIndex with the sql table model I had set with QCompleter::setModel(). I dont know how QCompleter works but I believe it internally derives a list model from the input table model.

From documentation -

QAbstractItemModel* QCompleter::completionModel()

Returns the completion model. The completion model is a read-only list model that contains all the possible matches for the current completion prefix. The completion model is auto-updated to reflect the current completions.

So now my SLOT looks like this -

void MainWindow::on_line_edit_returnPressed()
{
    QModelIndex index = ui->le_filter->completer()->currentIndex();
    if (index.isValid()) {
        int row = index.row();
        int key = completer->completionModel()->index(row, 0).data().toInt();
        qDebug() << key;
    }
}