问题描述:

I'm writing a GUI application with PyQt4 (Python3). One my friend pointed out that using pyuic4 is a bad practice and referred me to uic module and Connecting Slots By Name features. He didn't have time to explain more and the references I have are rather short, I couldn't grasp the idea from them (uic module, LoadingUIFilesAtRuntime, connecting slots by name).

On StackOverflow there is at least one related question but the links to the literature are broken there.

I could follow standard tutorials and did simple GUI using pyuic, but now feel a little bit confused... Any good examples and/or references are welcome.

Thanks.

网友答案:

Firstly, using pyuic4 is certainly not "bad practice".

There are three main ways to get PyQt4 UI's into your code:

  • Write it all by hand yourself
  • Use pyuic4 to auto-generate a python module that can be imported
  • Use the uic package to load ui files directly at runtime

Of these, the first two are by far the most common, and most documentation, tutorials, advice, etc that you will come across will use those methods.

A good source for PyQt4 tutorials can be found in this section of the PyQt4 Wiki. However, I should probably point out that, although still relevant, many of them are quite old and so still use the old-style signals and slots.

However, the difference between the old- and new- styles is not that difficult to understand, so maybe a simple example is all that's needed.

Here's the old-style way to connect a button-click signal to a handler method (aka slot):

self.connect(self.button, QtCore.SIGNAL('clicked()'), self.handleButtonClick)

and here's the new-style way:

self.button.clicked(self.handleButtonClick)

As you can see, the new-style is much simpler and more pythonic. On the other hand, the old-style is quite similar to how signals are connected using C++ (and for this reason can still be useful in certain circumstances).

If you have problems with connecting signals when writing your GUIs, you can always ask a question here - but it's much easier to get good answers if you ask specific questions that include example code.

相关阅读:
Top