How to modify style hint without QProxyStyle?

2019-03-01 02:27发布

问题:

I use Python bindings of Qt (PySide or PyQt4). They don't have QProxyStyle.

I want to change the value of a style hint. For example change the SH_Menu_SubMenuPopupDelay popup delay time of a submenu.

In native C++ Qt I would use a QProxyStyle and override styleHint and filter for the style hint of interest and return the value I like. It's done here for example.

But in the Python bindings I use QProxyStyle is not available. So how can a style hint of an existing style be modified there?

回答1:

The menu popup delay is not a fixed value, as it will depend on the current style. There is no way to set it programmatically.

The Qt way to modify style hints for existing styles is via QProxyStyle. However, even that is not guaranteed to work for user-defined or third-party styles, because they are not obliged to call QStyle.proxy(). And even if they did, neither PyQt nor PySide wrap any classes that are based on plugins (which includes QProxyStyle).

The only way to get full control over the behaviour of style-hints is to write your own, application-specific style class. But, of course, you would then no longer be modifying the style-hints of an existing style, so that is beyond the scope of the current question.

That seems to leave one remaining option, which is to subclass QMenu and bypass the style-hint altogether. Grepping the Qt source code reveals that (disregarding the various style classes) the only places where SH_Menu_SubMenuPopupDelay is used is within the mouseMoveEvent of QMenu. So it might be possible to reimplement that to get the behaviour you want.

UPDATE:

The QProxyStyle class is now available in PyQt5.