[Qt-interest] How to get an ID for a description selected in a QComboBox?

Marcelo Magno T. Sales mmtsales at gmail.com
Sun Jan 16 23:02:06 CET 2011


Em domingo 16 janeiro 2011, Stephen Kelly escreveu:
> Marcelo Magno T. Sales wrote:
> > Hello,
> > 
> > In a form, I have a QTableView which uses a QSqlTableModel. This
> > model should be filtered to select only those rows where the ID
> > field matches a value selected by the user in a QComboBox in this
> > form. However, the ID is a FK to another table. In the QComboBox,
> > which uses a model with two columns (ID and description), the
> > displayed values are the descriptions from that other table. When
> > the user selects a description in the QComboBox, I must be able to
> > get its ID to set the filter to the QTableView's model. What's the
> > best approach to achieve this? I couldn't find a way to get the
> > value of the ID for the selected description, nor to get the model
> > index for the selected value in the QComboBox.
> 
> Something like this?
> 
> connect(m_comboBox, SIGNAL(currentIndexChanged(int)),
> SLOT(updateFilter(int)));
> 
> void updateFilter(int row) {
>   const QModelIndex idx = m_comboBox->model()->index(row, 0);
>   const qint64 id = idx.data(MyModel::IdRole).toLongLong();
>   m_tableFilterModel->setFilterRegex(QString::number(id));
> }

Thanks very much. I had just managed to get the ID by changing the model 
column of the QComboBox to the ID column, reading the combo's 
currentText() and then changing its model column back to Description. 
However, doing things this way, I need to disconnect the 
currentIndexChanged(int) signal and reconnect it later to avoid 
recursion. 
The way you suggested is much cleaner.

Thanks,

Marcelo



More information about the Qt-interest-old mailing list