How to set filter parameter in QTableWidget

In my application, I have a QtableWidget displaying several lines, changing the line for entering a line and a button, the requirement says when you click the Same button, QtableWidget should show only those lines that have a line entered in line editing.

I thought to use the QSortFilterProxy Model, but the QtableWidget has the setModel(...) private method, so I cannot use the QSortFilterProxy Model in this case. Please let me know how to implement a filter parameter in a QTable Widget

+8
qt
source share
2 answers

Using a sort / filter proxy is probably too great for this.

This is a question with an iteration of all QTableWidgetItem objects that determine whether their text matches the filter and calls QTableView :: setRowHidden () as necessary.

For example:

 QString filter = textEdit->text(); for( int i = 0; i < table->rowCount(); ++i ) { bool match = false; for( int j = 0; j < table->columnCount(); ++j ) { QTableWidgetItem *item = table->item( i, j ); if( item->text().contains(filter) ) { match = true; break; } } table->setRowHidden( i, !match ); } 
+15
source share

I highly recommend doing this as follows! Here's how to do it in Qt.

Take a look at the Qt Model / View Programming tutorial . The problem is that QTableWidget is a convenience class that hides Model / View stuff for you. In your case, you cannot (or should not) ignore the Model / View structure provided by Qt.

What you need to do:

  • Use QTableView instead of QTableWidget .
  • Subclass QAbstractItemModel and implement data() (for reading) and all other functions that you need from the documentation . This is the hardest part, but refer to the link above to read how to do this.
  • Create a QSortFilterProxyModel and setModel() QTableView .
  • setSourceModel() your QSortFilterProxyModel to your subclass model.
  • Set the string you want to filter using setFilterFixedString() or setFilterRegExp() in QSortFilterProxyModel

Let me know if this helps. It is much more professional, and ultimately elegant, than repeating all the elements in your desk.

+15
source share

All Articles