Custom Widgets

One of PyQt's greatest and longest-standing strengths is the ease with which it is possible to create custom widgets. The custom widgets we create with PyQt are made the same way as the standard built-in widgets, so they integrate seamlessly and have no arbitrary restrictions on their appearance or behavior. Creating custom widgets in PyQt is not a matter of "one size fits all". Rather, we can choose from a number of approaches that give us increasing levels of control over our widgets' behavior and appearance.

The most basic level of customization is to simply set some of the properties of an existing widget. We have already done this a number of times in earlier chapters. For example, in the preceding chapter we enabled PyQt's default drag-and-drop behavior simply by calling setAcceptDrops(True) and setDragEnabled(True) on our widgets. For spinboxes, we can constrain their behavior—for example, by calling setRange() to set a minimum and maximum value—and can affect their appearance by using setPrefix() and setSuffix(). We will not show examples of this approach in this chapter because we have already seen it in action many times before.

If setting the properties of an existing widget is insufficient, we can use a style sheet to customize the widget's appearance and some aspects of its behavior. The ability to set style sheets on widgets was introduced with Qt 4.2, and we will see a simple example to give a taste of what is possible in this chapter.

Sometimes we need not so much to customize a particular widget, but to create a composite widget that combines two or more other widgets. We will look at a simple example of how this can be done.

If we need to change the behavior of an existing widget beyond what can be achieved by setting properties, we can subclass the widget and reimplement whichever event handlers are necessary to achieve the control we want.

But in some cases, we need a widget that is different from any of the standard built-in widgets. For these situations we can subclass QWidget directly and can completely define the behavior and appearance of the widget ourselves. We

will show two examples of this, the first a "generic" widget that might be used in many places and many applications and the second an application-specific widget of the kind that might be created for just one program.

Was this article helpful?

0 -1
100 SEO Tips and More

100 SEO Tips and More

100 SEO Tips EVERY SEO Enthusiast Should Know. This Report 100 SEO Tips will help you to Utilize These Tips to Dominate The Search Engine Today.

Get My Free Ebook


Post a comment