Sunday, March 10, 2013

Program View Line Numbers – Custom Item Delegates

It will be very helpful during testing if the program view displayed line numbers like the edit box.  This was accomplished with what Qt calls a custom item delegate.  An item delegate is responsible for drawing the items in a widget and widgets have a default delegate.

A new ProgramLineDelegate class was created with the QItemDelegate class as its base.  Since the program list view is read-only, the only function that needs to be reimplemented in this new class is the paint() function, which has arguments to the painter (used for drawing to the screen), the current style option (which contains information about the view item like its bounding rectangle), and an index of the item to paint.

To start simple, the line number is obtained from the row of the index and the text of the line is obtained from the model of the index (currently the QStringListModel setup to hold the program lines), which is used to get the string of the item that needs to be displayed.  These two items are formatted using the string "%1: %2" to put the line number followed by a colon and the string of the program line.  This string is then drawn to the screen using the painter's drawText() function.

This is crude, but was a proof of concept (this is my first time using delegates).  This will be cleaned up next by drawing the line number separately in its own rectangle with a different background color.  It will also need to determine the width of this rectangle based on the maximum line number like with the edit box.

[commit 941b1f8e75]

No comments:

Post a Comment

All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)