Ошибка setmodel is a private member of 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?

eyllanesc's user avatar

eyllanesc

233k19 gold badges163 silver badges235 bronze badges

asked Jul 16, 2009 at 13:48

crew4ok's user avatar

1

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.

answered Jul 16, 2009 at 17:18

Marc Mutz - mmutz's user avatar

Marc Mutz — mmutzMarc Mutz — mmutz

24.3k12 gold badges78 silver badges90 bronze badges

2

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).

answered Jul 16, 2009 at 14:06

Aaron Digulla's user avatar

Aaron DigullaAaron Digulla

320k108 gold badges596 silver badges816 bronze badges

4

QTableWidget:Details

The QTableWidget class provides an item-based table view with a default model.

Table widgets provide standard table display facilities for applications. The items in a QTableWidget are provided by QTableWidgetItem.

If you want a table that uses your own data model you should use QTableView rather than this class.

The widget class handles the model itself, if you want to use your own model use the View class.

You are correct that there does not seem to be methods for knowing the selection for the TableView or SQLModel. You could derive your own class from the TableView and track the current selection through the selectionChanged slot.

OR

Use the QTableView::selectionModel() and call selection(). This is similar to mmutz’s answer. Be sure to read that code for the gory details of actually getting to the record.

Community's user avatar

answered Jul 16, 2009 at 14:06

Jesse Vogt's user avatar

Jesse VogtJesse Vogt

16.2k16 gold badges59 silver badges72 bronze badges

1

I only used the model-view architecture once, but I’ll try to give you some general insight in that architecture, because it seems to me you don’t understand it very well yet. So this will probably be incomplete and simplified, but hopefully somewhat correct.

If you work with a view, you can provide you’re own model. If you work with a widget, then you dont work with a qt model, but insert items yourself. Preferably you work with a model to decouple things (so you can have more than one view for the same model, or change the model later on, …)

When you use a model the view will itself knows how to ask the model you provide to populate the view (using the data function). There are several ways to get a selection from this view: I have handled it by connecting the clicked signal, that the view emits when the user clicks in the view, to a slot function i wrote myself. The clicked signal provides an index of the table/list that I map to an item in my model in that slot function.

There are probably more ways to do it, but thats how I did it and it works fine.

To get a general grasp on the qt model-view architecture:

http://doc.trolltech.com/4.5/model-view-programming.html

answered Jul 16, 2009 at 17:19

Emile Vrijdags's user avatar

Emile VrijdagsEmile Vrijdags

1,5302 gold badges15 silver badges24 bronze badges

it is private in QTableWidget

class Q_GUI_EXPORT QTableWidget : public QTableView
{
...
...
private:
    void setModel(QAbstractItemModel *model);
...

it is public in QAbstractItemView

so you cant call this function from here…

check qtablewidget.h in includeQtqtablewidget.h

maybe it is not a good answer but at least it shows why it is not working…

answered Jul 16, 2009 at 13:59

ufukgun's user avatar

ufukgunufukgun

6,8598 gold badges32 silver badges55 bronze badges

ШКІПЕР

99 / 99 / 22

Регистрация: 14.04.2010

Сообщений: 280

Записей в блоге: 9

1

03.02.2014, 19:36. Показов 11882. Ответов 7

Метки qt, qtableview, qtablewidget (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет. Туплю жестоко…

Суть в чем:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
QTableWidget *test, *test3;   //это
QTableView *test2;               //подопытные 
//---
test = new QTableWidget(2,2);
QTableWidgetItem *twi = new QTableWidgetItem();
QTableWidgetItem *twi2 = new QTableWidgetItem();
test->setItem(0,0,twi);
test->setItem(0,1,twi2);
twi->setText("blablabla");
twi2->setText("blablabla");
//---
test2 = new QTableView();
test2->setModel(test->model()); // <-- без проблем
 
//QSqlTableModel *model = new QSqlTableModel();
//test2->setModel(model); // <-- без проблем
 
test3 = new QTableWidget();
//test3->setModel(test2->model()); //<-- так не пошло...

1. QTableWidget фактически наследник QTableView. В нем есть setModel, но он private… Вообще реально поместить каку-то модель (будь то даже QSqlTableModel) в QTableWidget?
2. Или это можно как-то по другому сделать?
3. Да, знаю, QTableView на много лучше в этом плане, но мне нужен именно QTableWidget…



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

03.02.2014, 19:36

7

Диссидент

Эксперт C

27513 / 17201 / 3786

Регистрация: 24.12.2010

Сообщений: 38,742

03.02.2014, 19:51

2

ШКІПЕР, Имхо, для QTableWidget модель назначит нельзя (она уже назначена), только для QTableView. Все, что можно сделать, это манипулировать содержимым QTableWidgetItem при заполнении ячеек…
Но это сугубое «ИМХО». Может быть специалисты подскажут другие лазейки.



0



99 / 99 / 22

Регистрация: 14.04.2010

Сообщений: 280

Записей в блоге: 9

03.02.2014, 22:55

 [ТС]

3

Байт, хм… Неужели только путь джедая с переписыванием половины либы…
А как-то можно транспортировать данные с QTableView в QTableWidget Qt-способами?



0



Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

03.02.2014, 23:58

4

А что смущает? отнаследовался от QAbstractTableModel и все, пример вроде в Шлее есть.



0



Байт

Диссидент

Эксперт C

27513 / 17201 / 3786

Регистрация: 24.12.2010

Сообщений: 38,742

04.02.2014, 00:34

5

Цитата
Сообщение от ШКІПЕР
Посмотреть сообщение

Неужели только путь джедая с переписыванием половины либы.

А какая конкретно стоит задача? Понимаю, что если уже есть наработки на QTableWidget, откатываться к его предку — в лом. И модельку рисовать, и с делегатами разбираться…Но мне вот удалось решить какие-то подобного рода проблемы через механизм ролей

C++ (Qt)
1
2
3
    QTableWidgetItem *twi = ....
    twi->setData(Qt::UserRole, q);
    twi->setData(Qt::UserRole+1, nf);

И когда с моей ячейкой чегой-то происходит, я ее сигнальчик ловлю в слоте, и там разбираюсь по

C++ (Qt)
1
data(Qt::UserRole)

А еще есть механизм динамических свойств…



1



99 / 99 / 22

Регистрация: 14.04.2010

Сообщений: 280

Записей в блоге: 9

04.02.2014, 01:04

 [ТС]

6

Цитата
Сообщение от Байт
Посмотреть сообщение

уже есть наработки на QTableWidget, откатываться к его предку — в лом

Ситуация именно такая
Вот даже на самом простом: необходимость сохранять (загружать) все данные с таблицы в sql (QSqlDatabase).
Сохранить через model() элементарно и буквально пару строчек а вот так же легко загрузить не выйдет… Всегда поможет старый добрый цикл, но это слишком банально…

Цитата
Сообщение от Байт
Посмотреть сообщение

механизм ролей

А какой смысл этого всего извращения?)



0



Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

04.02.2014, 01:11

7

Цитата
Сообщение от ШКІПЕР
Посмотреть сообщение

Ситуация именно такая

Лучше переделать …



1



Диссидент

Эксперт C

27513 / 17201 / 3786

Регистрация: 24.12.2010

Сообщений: 38,742

04.02.2014, 18:00

8

Цитата
Сообщение от ШКІПЕР
Посмотреть сообщение

А какой смысл этого всего извращения?)

Я попробовал. Мне понравилось. Кой-какие вещи получились естественно и легко. Ни на чем не настаиваю.
А смысл в том, что используя эту технику, мы получаем фактически расширение базового класса без наследования.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

04.02.2014, 18:00

Помогаю со студенческими работами здесь

QTableWidget
Добрый день, работаю с QTableWidget QTableview. Вопрос вот в чем: нужно создать таблицу, НО не…

QT 5.6 C++ QTableWidget
Здравствуйте!!!

Создал QTableWidget через дизайнер форм.

Разобрался как получить значение…

QTableWidget
При создании QTableWidget *tableWidget = new QTableWidget(3, 3, this); я указываю сколько будет…

QTableWidget
Как сделать чтобы при клике на строку или ячейку в QTableWidget она не выделялось тоесть вообще…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

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?

eyllanesc's user avatar

eyllanesc

233k19 gold badges163 silver badges235 bronze badges

asked Jul 16, 2009 at 13:48

crew4ok's user avatar

1

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.

answered Jul 16, 2009 at 17:18

Marc Mutz - mmutz's user avatar

Marc Mutz — mmutzMarc Mutz — mmutz

24.3k12 gold badges78 silver badges90 bronze badges

2

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).

answered Jul 16, 2009 at 14:06

Aaron Digulla's user avatar

Aaron DigullaAaron Digulla

320k108 gold badges596 silver badges816 bronze badges

4

QTableWidget:Details

The QTableWidget class provides an item-based table view with a default model.

Table widgets provide standard table display facilities for applications. The items in a QTableWidget are provided by QTableWidgetItem.

If you want a table that uses your own data model you should use QTableView rather than this class.

The widget class handles the model itself, if you want to use your own model use the View class.

You are correct that there does not seem to be methods for knowing the selection for the TableView or SQLModel. You could derive your own class from the TableView and track the current selection through the selectionChanged slot.

OR

Use the QTableView::selectionModel() and call selection(). This is similar to mmutz’s answer. Be sure to read that code for the gory details of actually getting to the record.

Community's user avatar

answered Jul 16, 2009 at 14:06

Jesse Vogt's user avatar

Jesse VogtJesse Vogt

16.2k16 gold badges59 silver badges72 bronze badges

1

I only used the model-view architecture once, but I’ll try to give you some general insight in that architecture, because it seems to me you don’t understand it very well yet. So this will probably be incomplete and simplified, but hopefully somewhat correct.

If you work with a view, you can provide you’re own model. If you work with a widget, then you dont work with a qt model, but insert items yourself. Preferably you work with a model to decouple things (so you can have more than one view for the same model, or change the model later on, …)

When you use a model the view will itself knows how to ask the model you provide to populate the view (using the data function). There are several ways to get a selection from this view: I have handled it by connecting the clicked signal, that the view emits when the user clicks in the view, to a slot function i wrote myself. The clicked signal provides an index of the table/list that I map to an item in my model in that slot function.

There are probably more ways to do it, but thats how I did it and it works fine.

To get a general grasp on the qt model-view architecture:

http://doc.trolltech.com/4.5/model-view-programming.html

answered Jul 16, 2009 at 17:19

Emile Vrijdags's user avatar

Emile VrijdagsEmile Vrijdags

1,5302 gold badges15 silver badges24 bronze badges

it is private in QTableWidget

class Q_GUI_EXPORT QTableWidget : public QTableView
{
...
...
private:
    void setModel(QAbstractItemModel *model);
...

it is public in QAbstractItemView

so you cant call this function from here…

check qtablewidget.h in includeQtqtablewidget.h

maybe it is not a good answer but at least it shows why it is not working…

answered Jul 16, 2009 at 13:59

ufukgun's user avatar

ufukgunufukgun

6,8598 gold badges32 silver badges55 bronze badges

ШКІПЕР

99 / 99 / 22

Регистрация: 14.04.2010

Сообщений: 280

Записей в блоге: 9

1

03.02.2014, 19:36. Показов 11866. Ответов 7

Метки qt, qtableview, qtablewidget (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет. Туплю жестоко…

Суть в чем:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
QTableWidget *test, *test3;   //это
QTableView *test2;               //подопытные 
//---
test = new QTableWidget(2,2);
QTableWidgetItem *twi = new QTableWidgetItem();
QTableWidgetItem *twi2 = new QTableWidgetItem();
test->setItem(0,0,twi);
test->setItem(0,1,twi2);
twi->setText("blablabla");
twi2->setText("blablabla");
//---
test2 = new QTableView();
test2->setModel(test->model()); // <-- без проблем
 
//QSqlTableModel *model = new QSqlTableModel();
//test2->setModel(model); // <-- без проблем
 
test3 = new QTableWidget();
//test3->setModel(test2->model()); //<-- так не пошло...

1. QTableWidget фактически наследник QTableView. В нем есть setModel, но он private… Вообще реально поместить каку-то модель (будь то даже QSqlTableModel) в QTableWidget?
2. Или это можно как-то по другому сделать?
3. Да, знаю, QTableView на много лучше в этом плане, но мне нужен именно QTableWidget…

0

Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

03.02.2014, 19:36

7

Диссидент

Эксперт C

27497 / 17185 / 3784

Регистрация: 24.12.2010

Сообщений: 38,714

03.02.2014, 19:51

2

ШКІПЕР, Имхо, для QTableWidget модель назначит нельзя (она уже назначена), только для QTableView. Все, что можно сделать, это манипулировать содержимым QTableWidgetItem при заполнении ячеек…
Но это сугубое «ИМХО». Может быть специалисты подскажут другие лазейки.

0

99 / 99 / 22

Регистрация: 14.04.2010

Сообщений: 280

Записей в блоге: 9

03.02.2014, 22:55

 [ТС]

3

Байт, хм… Неужели только путь джедая с переписыванием половины либы…
А как-то можно транспортировать данные с QTableView в QTableWidget Qt-способами?

0

Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

03.02.2014, 23:58

4

А что смущает? отнаследовался от QAbstractTableModel и все, пример вроде в Шлее есть.

0

Байт

Диссидент

Эксперт C

27497 / 17185 / 3784

Регистрация: 24.12.2010

Сообщений: 38,714

04.02.2014, 00:34

5

Цитата
Сообщение от ШКІПЕР
Посмотреть сообщение

Неужели только путь джедая с переписыванием половины либы.

А какая конкретно стоит задача? Понимаю, что если уже есть наработки на QTableWidget, откатываться к его предку — в лом. И модельку рисовать, и с делегатами разбираться…Но мне вот удалось решить какие-то подобного рода проблемы через механизм ролей

C++ (Qt)
1
2
3
    QTableWidgetItem *twi = ....
    twi->setData(Qt::UserRole, q);
    twi->setData(Qt::UserRole+1, nf);

И когда с моей ячейкой чегой-то происходит, я ее сигнальчик ловлю в слоте, и там разбираюсь по

C++ (Qt)
1
data(Qt::UserRole)

А еще есть механизм динамических свойств…

1

99 / 99 / 22

Регистрация: 14.04.2010

Сообщений: 280

Записей в блоге: 9

04.02.2014, 01:04

 [ТС]

6

Цитата
Сообщение от Байт
Посмотреть сообщение

уже есть наработки на QTableWidget, откатываться к его предку — в лом

Ситуация именно такая
Вот даже на самом простом: необходимость сохранять (загружать) все данные с таблицы в sql (QSqlDatabase).
Сохранить через model() элементарно и буквально пару строчек а вот так же легко загрузить не выйдет… Всегда поможет старый добрый цикл, но это слишком банально…

Цитата
Сообщение от Байт
Посмотреть сообщение

механизм ролей

А какой смысл этого всего извращения?)

0

Эксперт С++

8385 / 6147 / 615

Регистрация: 10.12.2010

Сообщений: 28,683

Записей в блоге: 30

04.02.2014, 01:11

7

Цитата
Сообщение от ШКІПЕР
Посмотреть сообщение

Ситуация именно такая

Лучше переделать …

1

Диссидент

Эксперт C

27497 / 17185 / 3784

Регистрация: 24.12.2010

Сообщений: 38,714

04.02.2014, 18:00

8

Цитата
Сообщение от ШКІПЕР
Посмотреть сообщение

А какой смысл этого всего извращения?)

Я попробовал. Мне понравилось. Кой-какие вещи получились естественно и легко. Ни на чем не настаиваю.
А смысл в том, что используя эту технику, мы получаем фактически расширение базового класса без наследования.

0

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

04.02.2014, 18:00

Помогаю со студенческими работами здесь

QTableWidget
Добрый день, работаю с QTableWidget QTableview. Вопрос вот в чем: нужно создать таблицу, НО не…

QT 5.6 C++ QTableWidget
Здравствуйте!!!

Создал QTableWidget через дизайнер форм.

Разобрался как получить значение…

QTableWidget
При создании QTableWidget *tableWidget = new QTableWidget(3, 3, this); я указываю сколько будет…

QTableWidget
Как сделать чтобы при клике на строку или ячейку в QTableWidget она не выделялось тоесть вообще…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

  • Home
  • Forum
  • Qt
  • Qt Programming
  • Is an error in doc whith QTableWidget::setModel?

  1. 1st January 2009, 22:38

    #1

    Default Is an error in doc whith QTableWidget::setModel?

    I wonder is the method QTableWidget::setModel reimplemented as a private? In Qt Reference Documentation it seems to be public?


  2. 2nd January 2009, 06:38

    #2

    Default Re: Is an error in doc whith QTableWidget::setModel?

    wha is version of Qt? I didn’t find setModel as public in docs in 4.4.3.

    Qt Assistant — rocks!
    please, use tags [CODE] & [/CODE].


  3. 2nd January 2009, 06:39

    #3

    Default Re: Is an error in doc whith QTableWidget::setModel?

    what is version of Qt? I didn’t find setModel as public in 4.4.3 docs.

    Qt Assistant — rocks!
    please, use tags [CODE] & [/CODE].


  4. 2nd January 2009, 07:54

    #4

    Default Re: Is an error in doc whith QTableWidget::setModel?

    I wonder is the method QTableWidget::setModel reimplemented as a private?

    YES !
    In docs, you are seeing QAbstractItemView::setModel .

    QTableWidget manages its own internal model. If you want to use model, use it with QTableView


  5. 2nd January 2009, 08:18

    #5

    Default Re: Is an error in doc whith QTableWidget::setModel?

    yup, setModel() can be used only with item view classes like QListView, QTableView, QTreeView etc. For QTableWidget, you can’t play with the model directly.


  6. 3rd January 2009, 15:00

    #6

    Default Re: Is an error in doc whith QTableWidget::setModel?

    QTableWidget manages its own internal model. If you want to use model, use it with QTableView

    But it not result from docs. This method exists in list of inherited method.

    Thanks!


  7. 5th January 2009, 06:41

    #7

    Default Re: Is an error in doc whith QTableWidget::setModel?

    Well, you can refer in source code for QTableWidget.
    And you are right, setModel shows in list of all methods for QTableWidget. May be its a mistake.


  8. 5th January 2009, 08:51

    #8

    Default Re: Is an error in doc whith QTableWidget::setModel?

    It is a method of the base class of QTableWidget so why shouldn’t it be listed there? The documentation clearly says it’s a list of all methods including inherited ones. It’s just reimplemented as private so that you don’t have a stupid idea of calling it and segfaulting your application on the first reference to the widget.


  9. 5th January 2009, 16:53

    #9

    Default Re: Is an error in doc whith QTableWidget::setModel?

    The documentation clearly says it’s a list of all methods including inherited ones.

    Yes, but documentation shows only public method, and also should show inherited public method.

    It’s just reimplemented as private so

    Where it is written?

    you don’t have a stupid idea of calling it and segfaulting your application on the first reference to the widget.

    For you knowledge, you can’t compile program where you use virtual method reimplemented as private!
    And I have a favour to ask of you Can you be more polite?


  10. 5th January 2009, 20:07

    #10

    Default Re: Is an error in doc whith QTableWidget::setModel?

    Quote Originally Posted by mikolaj
    View Post

    Yes, but documentation shows only public method, and also should show inherited public method.

    When you access the «all method» page, all methods are shown. When you access the base documentation page, only those declared in this particular class are mentioned. SetModel() is declared in the base class and specifically hidden in the subclass. As you see no private methods are mentioned in any docs.Here:
    «If you want a table that uses your own data model you should use QTableView rather than this class.»

    For you knowledge, you can’t compile program where you use virtual method reimplemented as private!

    That’s the whole idea of it being redeclared as private. If it remained public you could have compiled it and thus wrecked the application without any possiblility of knowing why and you would have blamed Qt code for it as the debugger would clearly indicate the crash was caused by Qt code and not yours.

    And I have a favour to ask of you Can you be more polite?

    Where have I been impolite? By using the word «stupid»? I don’t think there is anything impolite there, I do stupid things as well, there is nothing wrong in making mistakes and calling ones actions such, especially if you learn from them. Please note I didn’t call you stupid, I said the method is private to stop stupid ideas of using it where it is not appropriate. You can’t imagine what people are trying to do with Qt code If your ideas felt offended by my words, I appologize to them.


  11. 6th January 2009, 21:44

    #11

    Default Re: Is an error in doc whith QTableWidget::setModel?

    But I think, it would be more comfortable if the method public in parent not available in children was mentioned in docs.


  12. 8th January 2009, 20:31

    #12

    Default Re: Is an error in doc whith QTableWidget::setModel?

    From QTableWidget docs, right from the beginning of the detailed description:

    The QTableWidget class provides an item-based table view

    with a default model

    .

    If you want a table that uses your own data model you should use QTableView rather than this class.

    J-P Nurmi


Bookmarks

Bookmarks


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.

This topic has been deleted. Only users with topic management privileges can see it.

  • I’m trying to perform search a in QTableWidget using QSortFilterProxyModel() but I’m getting an error message saying self.ui.tableWidget.setModel(filter_proxy_model)
    TypeError: QTableWidget.setModel() is a private method
    . Please I need assistance, below is the code I used. Thanks in advance.

       companies = ('Apple', 'Facebook', 'Google', 'Amazon', 'Walmart', 'Dropbox', 'Starbucks', 'eBay', 'Canon')
            model = QStandardItemModel(len(companies), 1)
            model.setHorizontalHeaderLabels(['Company'])
    
            for row, company in enumerate(companies):
                item = QStandardItem(company)
                model.setItem(row, 0, item)
    
            filter_proxy_model = QSortFilterProxyModel()
            filter_proxy_model.setSourceModel(model)
            filter_proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
            filter_proxy_model.setFilterKeyColumn(0)
    
    
            self.ui.lineEdit.textChanged.connect(filter_proxy_model.setFilterRegExp)
    
          
            self.ui.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
            self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            self.ui.tableWidget.setModel(filter_proxy_model)
    
  • @LT-K101
    Although I cannot actually see it documented, the error message QTableWidget.setModel() is a private method tells you that you cannot call setModel() directly on a QTableWidget. You would have to subclass it to avoid this message.

    However, I don’t think QTableWidget supports you changing its model. It has an internal model which it wishes to use. If you want to interpose a QSortFilterProxyModel you probably need to move to a QTableView.

    See also https://stackoverflow.com/questions/1137732/setting-the-model-to-a-qtablewidget

  • @LT-K101
    Although I cannot actually see it documented, the error message QTableWidget.setModel() is a private method tells you that you cannot call setModel() directly on a QTableWidget. You would have to subclass it to avoid this message.

    However, I don’t think QTableWidget supports you changing its model. It has an internal model which it wishes to use. If you want to interpose a QSortFilterProxyModel you probably need to move to a QTableView.

    See also https://stackoverflow.com/questions/1137732/setting-the-model-to-a-qtablewidget

  • Hi,

    As @JonB rightly pointed, QTableWidget is a convenience widget that is provided with model included as well as dedicated item class.

    You are anyway creating your own model for your companies so using QTableWidget would not make sense in any case. So use QTableView. In the absolute, you have a single column model so it would even make more sense to use a QListView and since it’s a string list, the QStringListModel.

  • @JonB Thanks QTableView solved the error.

  • @SGaist Thanks a lot for your response. What I want to actually implement is, I want to use say two columns in my database table as search parameters namely First Name and Last Name.So when the user press a letter in a search field(lineEdit) the search will return all the words having the letter pressed to be displayed in a QTableView. Can I use the approach above to accomplished this?Any advice. Thanks

  • You are mentioning database, are you using a SQL database ?

  • @SGaist You right Sqlite database

  • So the next question is whether you want the database to do the filtering or the proxy model.

  • @SGaist Yes you right , so I wanted to use the key press event with an sql LIKE statement. Do you think that will be feasible?

  • @LT-K101
    Yes it would be «feasible».

    However, using key press event (or text changed signal on a line edit) sounds like you would want to append to the LIKE and re-issue a SQL query for each key. That is «expensive»! Might be OK on, say, a local SQLite database, not so keen on, say, a remote MySQL database. Or, «accumulate» key presses/changed signals over a small period, like till 1 second has passed since the last character added, and only re-issue the query then.

    Of course if the data rows are small you can afford to read data in and use Qt client-side filtering instead.

    You could also use a QCompleter, depending on your data size and speed.

  • @JonB Thanks I used textChanged[str] signal and it worked!

  • Solution 1

    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.

    Solution 2

    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).

    Comments

    • 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?

    • I need to use QTableView because of public setModel() function, but QTableView hasnt selectedItems() function. P.S. Sorry for my English.

    • As I understand, I have to use it with clicked() signal.But when i’m checking if the QList is empty I get that it’s empty.=/

    • If you use QAbstractItemView::clicked(QModelIndex), the QModelIndex is passed as a signal argument. The above code is for the case that you want to see what the selected records are. In the clicked() case, you just need the two lines inside the Q_FOREACH, with mi being the QModelIndex coming from the signal.

    • There is a typo above: It should say that QTableWidget has a built-in model, not QTableView.

    • Careful. You don’t want selectionModel here: that’s the type used to handle selecting items in the view by, e.g. using Shift-click. The internal data model is simply the model property of a view.

    Recents

    Related

    • Home
    • Forum
    • Qt
    • Qt Programming
    • Is an error in doc whith QTableWidget::setModel?

    1. 1st January 2009, 22:38


      #1

      Default Is an error in doc whith QTableWidget::setModel?

      I wonder is the method QTableWidget::setModel reimplemented as a private? In Qt Reference Documentation it seems to be public?


    2. 2nd January 2009, 06:38


      #2

      Default Re: Is an error in doc whith QTableWidget::setModel?

      wha is version of Qt? I didn’t find setModel as public in docs in 4.4.3.

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    3. 2nd January 2009, 06:39


      #3

      Default Re: Is an error in doc whith QTableWidget::setModel?

      what is version of Qt? I didn’t find setModel as public in 4.4.3 docs.

      Qt Assistant — rocks!
      please, use tags [CODE] & [/CODE].


    4. 2nd January 2009, 07:54


      #4

      Default Re: Is an error in doc whith QTableWidget::setModel?

      I wonder is the method QTableWidget::setModel reimplemented as a private?

      YES !
      In docs, you are seeing QAbstractItemView::setModel .

      QTableWidget manages its own internal model. If you want to use model, use it with QTableView


    5. 2nd January 2009, 08:18


      #5

      Default Re: Is an error in doc whith QTableWidget::setModel?

      yup, setModel() can be used only with item view classes like QListView, QTableView, QTreeView etc. For QTableWidget, you can’t play with the model directly.


    6. 3rd January 2009, 15:00


      #6

      Default Re: Is an error in doc whith QTableWidget::setModel?

      QTableWidget manages its own internal model. If you want to use model, use it with QTableView

      But it not result from docs. This method exists in list of inherited method.

      Thanks!


    7. 5th January 2009, 06:41


      #7

      Default Re: Is an error in doc whith QTableWidget::setModel?

      Well, you can refer in source code for QTableWidget.
      And you are right, setModel shows in list of all methods for QTableWidget. May be its a mistake.


    8. 5th January 2009, 08:51


      #8

      Default Re: Is an error in doc whith QTableWidget::setModel?

      It is a method of the base class of QTableWidget so why shouldn’t it be listed there? The documentation clearly says it’s a list of all methods including inherited ones. It’s just reimplemented as private so that you don’t have a stupid idea of calling it and segfaulting your application on the first reference to the widget.


    9. 5th January 2009, 16:53


      #9

      Default Re: Is an error in doc whith QTableWidget::setModel?

      The documentation clearly says it’s a list of all methods including inherited ones.

      Yes, but documentation shows only public method, and also should show inherited public method.

      It’s just reimplemented as private so

      Where it is written?

      you don’t have a stupid idea of calling it and segfaulting your application on the first reference to the widget.

      For you knowledge, you can’t compile program where you use virtual method reimplemented as private!
      And I have a favour to ask of you Can you be more polite?


    10. 5th January 2009, 20:07


      #10

      Default Re: Is an error in doc whith QTableWidget::setModel?

      Quote Originally Posted by mikolaj
      View Post

      Yes, but documentation shows only public method, and also should show inherited public method.

      When you access the «all method» page, all methods are shown. When you access the base documentation page, only those declared in this particular class are mentioned. SetModel() is declared in the base class and specifically hidden in the subclass. As you see no private methods are mentioned in any docs.Here:
      «If you want a table that uses your own data model you should use QTableView rather than this class.»

      For you knowledge, you can’t compile program where you use virtual method reimplemented as private!

      That’s the whole idea of it being redeclared as private. If it remained public you could have compiled it and thus wrecked the application without any possiblility of knowing why and you would have blamed Qt code for it as the debugger would clearly indicate the crash was caused by Qt code and not yours.

      And I have a favour to ask of you Can you be more polite?

      Where have I been impolite? By using the word «stupid»? I don’t think there is anything impolite there, I do stupid things as well, there is nothing wrong in making mistakes and calling ones actions such, especially if you learn from them. Please note I didn’t call you stupid, I said the method is private to stop stupid ideas of using it where it is not appropriate. You can’t imagine what people are trying to do with Qt code If your ideas felt offended by my words, I appologize to them.


    11. 6th January 2009, 21:44


      #11

      Default Re: Is an error in doc whith QTableWidget::setModel?

      But I think, it would be more comfortable if the method public in parent not available in children was mentioned in docs.


    12. 8th January 2009, 20:31


      #12

      Default Re: Is an error in doc whith QTableWidget::setModel?

      From QTableWidget docs, right from the beginning of the detailed description:

      The QTableWidget class provides an item-based table view

      with a default model

      .

      If you want a table that uses your own data model you should use QTableView rather than this class.

      J-P Nurmi


    Bookmarks

    Bookmarks


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •  
    • BB code is On
    • Smilies are On
    • [IMG] code is On
    • [VIDEO] code is On
    • HTML code is Off

    Forum Rules

    Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.

    This topic has been deleted. Only users with topic management privileges can see it.

  • I’m trying to perform search a in QTableWidget using QSortFilterProxyModel() but I’m getting an error message saying self.ui.tableWidget.setModel(filter_proxy_model)
    TypeError: QTableWidget.setModel() is a private method
    . Please I need assistance, below is the code I used. Thanks in advance.

       companies = ('Apple', 'Facebook', 'Google', 'Amazon', 'Walmart', 'Dropbox', 'Starbucks', 'eBay', 'Canon')
            model = QStandardItemModel(len(companies), 1)
            model.setHorizontalHeaderLabels(['Company'])
    
            for row, company in enumerate(companies):
                item = QStandardItem(company)
                model.setItem(row, 0, item)
    
            filter_proxy_model = QSortFilterProxyModel()
            filter_proxy_model.setSourceModel(model)
            filter_proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
            filter_proxy_model.setFilterKeyColumn(0)
    
    
            self.ui.lineEdit.textChanged.connect(filter_proxy_model.setFilterRegExp)
    
          
            self.ui.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
            self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            self.ui.tableWidget.setModel(filter_proxy_model)
    
  • @LT-K101
    Although I cannot actually see it documented, the error message QTableWidget.setModel() is a private method tells you that you cannot call setModel() directly on a QTableWidget. You would have to subclass it to avoid this message.

    However, I don’t think QTableWidget supports you changing its model. It has an internal model which it wishes to use. If you want to interpose a QSortFilterProxyModel you probably need to move to a QTableView.

    See also https://stackoverflow.com/questions/1137732/setting-the-model-to-a-qtablewidget

  • @LT-K101
    Although I cannot actually see it documented, the error message QTableWidget.setModel() is a private method tells you that you cannot call setModel() directly on a QTableWidget. You would have to subclass it to avoid this message.

    However, I don’t think QTableWidget supports you changing its model. It has an internal model which it wishes to use. If you want to interpose a QSortFilterProxyModel you probably need to move to a QTableView.

    See also https://stackoverflow.com/questions/1137732/setting-the-model-to-a-qtablewidget

  • Hi,

    As @JonB rightly pointed, QTableWidget is a convenience widget that is provided with model included as well as dedicated item class.

    You are anyway creating your own model for your companies so using QTableWidget would not make sense in any case. So use QTableView. In the absolute, you have a single column model so it would even make more sense to use a QListView and since it’s a string list, the QStringListModel.

  • @JonB Thanks QTableView solved the error.

  • @SGaist Thanks a lot for your response. What I want to actually implement is, I want to use say two columns in my database table as search parameters namely First Name and Last Name.So when the user press a letter in a search field(lineEdit) the search will return all the words having the letter pressed to be displayed in a QTableView. Can I use the approach above to accomplished this?Any advice. Thanks

  • You are mentioning database, are you using a SQL database ?

  • @SGaist You right Sqlite database

  • So the next question is whether you want the database to do the filtering or the proxy model.

  • @SGaist Yes you right , so I wanted to use the key press event with an sql LIKE statement. Do you think that will be feasible?

  • @LT-K101
    Yes it would be «feasible».

    However, using key press event (or text changed signal on a line edit) sounds like you would want to append to the LIKE and re-issue a SQL query for each key. That is «expensive»! Might be OK on, say, a local SQLite database, not so keen on, say, a remote MySQL database. Or, «accumulate» key presses/changed signals over a small period, like till 1 second has passed since the last character added, and only re-issue the query then.

    Of course if the data rows are small you can afford to read data in and use Qt client-side filtering instead.

    You could also use a QCompleter, depending on your data size and speed.

  • @JonB Thanks I used textChanged[str] signal and it worked!

  • Понравилась статья? Поделить с друзьями:
  • Ошибка set на киа рио
  • Ошибка set user settings to driver failed windows
  • Ошибка set controller to disabled and reconnect фейсит
  • Ошибка session php в joomla
  • Ошибка service theft deterrent system