ariya.io About Talks Articles

Alternating row colors, in group

2 min read

Alternating row colors is a very common user interface pattern, the most used example is the playlist in Apple iTunes. With different color every other row, the table or a long list looks more pleasant and easier to use.

However, if your list is rather vertical than horizontal, i.e. it is not that wide, but rather quite tall, and only consists of one or two columns, sometimes it helps to color not every row but a group of row. The example is shown here. The leftmost list widget has the same white color for all rows, the middle one uses alternating row colors (which looks rather “busy”), and the last one colors every 3 rows. Which one do you think is better?

Plain color

Row

Grouped

If your list is an instance of QListWidget, QListView or anything derived from QAbstractItemView, it is very easy to enable the alternating colors, just use alternatingRowColors property.

Alas, for grouped alternating colors for QListWidget, you must do some additional work, e.g. (works well for rather static items):

int group = 3;
  list->setUpdatesEnabled( false );
  for(int i = 0; i < list->count(); i++)
  {
    QListWidgetItem* item = list->item(i);
    QBrush c = ((int)(i/group))&1 ? palette().base() : palette().alternateBase();
    item->setBackground( c );
  }
  list->setUpdatesEnabled( true );

Multiple column list is often made from QTreeWidget with only top level tree items. In this case, grouped alternating colors can be achieved using e.g. (for two columns, create a loop for more):

int group = 3;
    tree->setUpdatesEnabled( false );
    for(int i = 0; i < tree->topLevelItemCount(); i++)
    {
      QTreeWidgetItem* item = tree->topLevelItem(i);
      QBrush c = ((int)(i/group))&1 ? palette().base() : palette().alternateBase();
      item->setBackground( 0, c );
      item->setBackground( 1, c );
    }
    tree->setUpdatesEnabled( true );

You can of course save some microseconds if you cycle the background color while iterating the items.

In addition, you may want to put some logic to prevent coloring if the number is item is e.g. less that 2*group. Otherwise, 4-item list will look odd, as only the last item has different background color.

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook