Setting the model to a QTableWidget


I want to write an application that can access a table in the database. I took QSqlTableModel as model component for the table.

The problem with the QTableView is that it seems to have no method that returns the currently selected record in the table so i took the QTableWidget class which interhits QTableView.

But when i try to set the model to this table widget with ->setModel() i get

the following error message:

c:/Qt/qt/include/QtGui/../../src/gui/itemviews/qtablewidget.h:337: error: `virtual void QTableWidget::setModel(QAbstractItemModel*)' is private.

The message says that the method "setModel" is private. Looking into the documentation tells me that it is public.

What can I do?

9/4/2017 4:42:00 PM

Accepted Answer

As others have noted, it's not QTableWidget that you want. It's indeed QTableView. Getting the records is then done like this:

static QList<QSqlRecord> selected_records( const QTableView * tv ) {
    // make sure we're really dealing with what we think we're dealing with:
    assert( static_cast<QSqlTableModel*>( tv->model() )
            == qobject_cast<QSqlTableModel*>( tv->model() );
    const QSqlTableModel * const tm = static_cast<QSqlTableModel*>( tv->model() );
    const QModelIndexList mil = tv->selectionModel()->selectedRows();
    QList<QSqlRecord> result;
    Q_FOREACH( const QModelIndex & mi, mil )
        if ( mi.isValid() )
            result.push_back( tm->record( mi.row() ) );
    return result;

If, OTOH, you are working in a slot connected to the - say - clicked(QModelIndex) signal of QTableView (really: QAbstractItemView), then this code is what you want:

void slotClicked( const QModelIndex & mi ) {
    // make sure we're really dealing with what we think we're dealing with:
    assert( static_cast<QSqlTableModel*>( tableView->model() )
            == qobject_cast<QSqlTableModel*>( tableView->model() );
    const QSqlRecord rec = static_cast<QSqlTableModel*>( tableView->model() )
               ->record( mi.row() );
    // use 'rec'

Yes, Qt could have that built-in, and esp. QSqlTableModel could have a more convenient way to map a QModelIndex back to a QSqlRecord, but there you go.

7/17/2009 12:16:57 PM

The method is public at the level of QAbstractItemView but QTableWidget has a built-in model which you can't change.

To get the selection, you must call selectedItems() (which is again a method of QAbstractItemView and not QTableView which is why you missed it in the docs).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow