Question

I have a QSqlQueryModel table. The user can see and access this. I want to know which row/rows that the user selects.

I have looked through a lot of other posts and documentations from qt-centre and I think the closest I believe is to somehow use QModelIndex, as shown here:

// for QSqlQueryModel or subclasses:
QSqlQueryModel *qmod = qobject_cast<QSqlQueryModel*>(md);
if(!qmod) return false;
QSqlRecord rec = qmod->record(curr.row()); // you have data inside the "rec" object

taken from http://www.qtcentre.org/archive/index.php/t-3104.html.

However this doesn't work for me. I don't want to use Qtableview as I want to work with only sqlQueryModel.

How do I detect user selections?

Thanks!

Was it helpful?

Solution

QTableView has a selection model. You can use the currentRowChanged signal of that selection model:

YourWidget : public QWidget
{
   Q_OBJECT
public:
   YourWidget(QWidget *parent = 0);
private slots:
   void onRowChanged(QModelIndex index);
}

YourWidget::YourWidget (QWidget *parent) :
    QWidget(paret)
{
    ...
    QTableView *view = new QTableView;
    view->setModel(yourModel);
    connect(view->selectionModel(), 
            SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), 
            this, 
            SLOT(onRowChanged(QModelIndex)));
    ...
}


void YourWidget::onRowChanged(QModelIndex index)
{
    int row = index.row();
    QSqlRecord rec = yourModel->record(row);
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top