Summary

PyQt's convenience item view widgets, such as QListWidget, QTableWidget, and QTreeWidget, are very useful for viewing and editing small and ad hoc datasets. They can be used in conjunction with external datasets as we did in the first section, or they can be used as data containers in their own right. Adding, editing, and removing items is straightforward, but if we use more than one view to show one dataset, we must accept the responsibility for keeping the views and dataset in sync. This problem goes away if we use the model/view approach with a custom model.

The convenience views do not provide any control over the editing of the items they handle. This deficiency is easy to rectify, both for convenience views and for pure views, by setting our own custom item delegate.

The pure views provide similar functionality to the convenience views, but do not provide sorting or direct control over the appearance of data items. These views must be used in conjunction with a model, whether a predefined one provided with PyQt, or more commonly, our own custom model.

To implement a custom table model we must reimplement rowCount(), column-Count(), and data() for both read-only and editable models; it is also usual to reimplement headerData(). In addition, we must implement flags() and set-Data() to make items editable, and insertRows() and removeRows() to allow users to insert or remove rows of data. If we want the user to be able to sort the data we can add additional sort methods, although in the case of database tables we can simply add ORDER BY clauses. Using databases with the model/view architecture is covered in the next chapter.

Creating custom delegates allows us to exercise complete control over the appearance and editing of data items. It is possible to share the responsibility for data appearance between the model and the delegate, or to give all of the responsibility to either of them. But only a custom delegate can be used to provide control over editing. For read-only delegates, and for delegates where we are concerned only with the appearance of data, we normally need to reimplement only the paint() method, although in some cases we must also reimplement sizeHint() (or handle the Qt.SizeHintRole in the model's data()

reimplementation). For most delegates, we don't need to reimplement paint() or sizeHint() at all, and only reimplement createEditor(), setEditorData(), and setModelData().

In the next chapter we will see further examples of the model/view architecture, with pure views, custom delegates, and built-in SQL database models.

Was this article helpful?

0 -1
Video Marketing Gold

Video Marketing Gold

Do you already know the huge impact that video could have on your online business BUT have no idea where to begin with it? Discover Exactly How You Can Start Taking Advantage of Video Marketing In Your Online Business... Even If You're a Total Newbie... Starting Today.

Get My Free Ebook


Post a comment