PDA

View Full Version : Using QSortFilterProxyModel with QTableWidgets



kremuwa
30th September 2010, 08:51
Hello,

I'm creating a database program, which contains one QTableWidget "tableSongs" that displays the whole data of a database.

It has 6 columns: 4 of them contain numbers, one contains text string and the last one contains sets of chars like "1A", "1B", "2A", "32G" or "111E" - it consists of a number (1-3 digits) and one upcase letter.

What I want to do is to add sorting and filtering functionality - columns with numbers should be sorted using numbers' value, column with strings - alphabetically and the last one like that: "1A" < "1B" but "9Z" < "19Z".

I thought that QSortFilterProxyModel would be a good class to use here.
I created second QTableWidget "tableSource" but didn't placed in on the window. I'm inserting rows and adding items to tableSource and I want QSortFilterProxyModel to show them in tableSongs after doing the sorting and filtering. But I have problems with doing so. Here is my code:


QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(tableSource.model());
tableSongs->setModel(proxyModel);

But it doesn't work. How should I correct it?

tbscope
30th September 2010, 09:11
You do not need to create a second view.

This is the basic schematic:

+--------------+ +-----------------------+ +----------+
| Source model +---+ Proxy model (sorting) +---+ The view |
+--------------+ +-----------------------+ +----------+

However, I think you'll need to create your own sorting routine as the items you want to sort are strings, and they sort differently than integers.

kremuwa
30th September 2010, 16:22
But is there as convenient solution basing on a model as using QTableWidget which has all of these "insert/removeRow", "clearContents" slots?

The sorting will be the next problem, but at the moment my problem is the communicate, which I receive after trying to compile:

proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(tableSource.model());
ui.tableSongs->setModel(proxyModel);

The communicate is as follows:

...src/gui/itemviews/qtablewidget.h:338: error: 'virtual void QTableWidget::setModel(QAbstractItemModel*)' is private

To be accurate, my "tableSongs" is not pure QTableWidget - I have promoted it to "upgTableWidget" - QTableWidget subclass. Can it be the reason of the error?

Lykurg
30th September 2010, 16:26
Is there any reason why you won't use QTableView with a QStandardItemModel or any other model?

kremuwa
30th September 2010, 17:12
Instead of "tableSongs"?

Lykurg
30th September 2010, 17:32
Instead of "tableSongs"?
yes, because then you wouldn't have the problem with a private model handling. And beside model/view is the higher approach then using *Widget.