Monday, July 1, 2013

How to add a computed column

My current goal is to add an extra column to the SelectorLibraryTableModel class that contains a "similarity score" for each row in the model. This score will be calculated on-the-fly in relation to a seed track.

My first approach was to override the columnCount, flags, headerData, and data functions inherited from LibraryTableModel, to create the illusion of an additional column in the model. (See this Qt forum post for a minimal example.) This new column displayed correctly in the WTrackTableView, but because it did not exist in the underlying SQL table, the BaseSqlTableModel could not use it to sort.

It might be possible to use that approach if I additionally overrided select and orderByClause, but it seems messy. One alternative might be to use a temporary table, following a procedure like this:

  1. Do setTableModel as usual to create the "library_view," without the score column.
  2. As filters are added and the selected set gets smaller, check in rowCount if the rows are below a certain critical value (say 100 rows).
  3. Once rowCount drops below the critical value, create a temporary table based on the current SQL query, and add the "score" column to it, i.e.:

    CREATE TEMP TABLE selector AS (SELECT * FROM library_view);
    ALTER TABLE selector ADD COLUMN score REAL;
  4. Calculate the similarity scores and update the temporary table with them.

  5. Set the table model to this temporary table.

This has the benefit that sorting would work as expected and only rowCount and setTableModel would have to be overridden. Potential problems with this approach:

  • If the filters change, the old temporary table has to be dropped and a new one created. That could get expensive.
  • Others?

No comments:

Post a Comment