Pyqt Designer Signals And Slots

Qt Designer is the Qt tool for designing and building graphical userinterfaces. It allows you to design widgets, dialogs or complete main windowsusing on-screen forms and a simple drag-and-drop interface. It has the abilityto preview your designs to ensure they work as you intended, and to allow youto prototype them with your users, before you have to write any code.

Qt Designer uses XML .ui files to store designs and does not generate anycode itself. Qt includes the uic utility that generates the C++ code thatcreates the user interface. Qt also includes the QUiLoader class thatallows an application to load a .ui file and to create the correspondinguser interface dynamically.

PyQt5 signals and slots Graphical applications (GUI) are event-driven, unlike console or terminal applications. A users action like clicks a button or selecting an item in a list is called an event. If an event takes place, each PyQt5 widget can emit a signal. Signals and slots are loosely coupled: A class which emits a signal neither knows nor cares which slots receive the signal. Qt's signals and slots mechanism ensures that if you connect a signal to a slot, the slot will be called with the signal's parameters at the right time. Signals and slots can take any number of arguments of any type. Each PyQt widget, which is derived from QObject class, is designed to emit ‘signal’ in response to one or more events. The signal on its own does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can be any callable Python function.

PyQt does not wrap the QUiLoader class but instead includes theuic Python module. Like QUiLoader this module can load.ui files to create a user interface dynamically. Like the uicutility it can also generate the Python code that will create the userinterface. PyQt’s pyuic4 utility is a command line interface to theuic module. Both are described in detail in the followingsections.

Using the Generated Code¶

The code that is generated has an identical structure to that generated by Qt’suic and can be used in the same way.

The code is structured as a single class that is derived from the Pythonobject type. The name of the class is the name of the toplevel object setin Designer with Ui_ prepended. (In the C++ version the class is definedin the Ui namespace.) We refer to this class as the form class.

The class contains a method called setupUi(). This takes a single argumentwhich is the widget in which the user interface is created. The type of thisargument (typically QDialog, QWidget or QMainWindow) is set inDesigner. We refer to this type as the Qt base class.

In the following examples we assume that a .ui file has been createdcontaining a dialog and the name of the QDialog object is ImageDialog.We also assume that the name of the file containing the generated Python codeis ui_imagedialog.py. The generated code can then be used in a numberof ways.

The first example shows the direct approach where we simply create a simpleapplication to create the dialog:

The second example shows the single inheritance approach where we sub-classQDialog and set up the user interface in the __init__() method:

The third example shows the multiple inheritance approach:

It is also possible to use the same approach used in PyQt v3. This is shown inthe final example:

For a full description see the Qt Designer Manual in the Qt Documentation.

The uic Module¶

The uic module contains the following functions and objects.

PyQt4.uic.widgetPluginPath

The list of the directories that are searched for widget plugins.Initially it contains the name of the directory that contains the widgetplugins included with PyQt.

PyQt4.uic.compileUi(uifile, pyfile[, execute=False[, indent=4[, pyqt3_wrapper=False[, from_imports=False]]]])

Generate a Python module that will create a user interface from a QtDesigner .ui file.

Parameters:
  • uifile – the file name or file-like object containing the .ui file.
  • pyfile – the file-like object to which the generated Python code will be writtento.
  • execute – is optionally set if a small amount of additional code is to begenerated that will display the user interface if the code is run as astandalone application.
  • indent – the optional number of spaces used for indentation in the generatedcode. If it is zero then a tab character is used instead.
  • pyqt3_wrapper – is optionally set if a small wrapper is to be generated that allows thegenerated code to be used as it is by PyQt v3 applications.
  • from_imports – is optionally set to generate import statements that are relative to'.'. At the moment this only applies to the import of resourcemodules.
Slots
PyQt4.uic.compileUiDir(dir[, recurse=False[, map=None[, **compileUi_args]]])

Create Python modules from Qt Designer .ui files in a directory ordirectory tree.

Parameters:
  • dir – the name of the directory to scan for files whose name ends with.ui. By default the generated Python module is created in the samedirectory ending with .py.
  • recurse – is optionally set if any sub-directories should be scanned.
  • map – an optional callable that is passed the name of the directorycontaining the .ui file and the name of the Python module that willbe created. The callable should return a tuple of the name of thedirectory in which the Python module will be created and the (possiblymodified) name of the module.
  • compileUi_args – are any additional keyword arguments that are passed tocompileUi() that is called to create each Pythonmodule.
PyQt4.uic.loadUiType(uifile[, from_imports=False])

Load a Qt Designer .ui file and return a tuple of the generatedform class and the Qt base class. These can then be used tocreate any number of instances of the user interface without having toparse the .ui file more than once.

Parameters:
  • uifile – the file name or file-like object containing the .ui file.
  • from_imports – is optionally set to use import statements that are relative to'.'. At the moment this only applies to the import of resourcemodules.
Return type:

the form class and the Qt base class.

PyQt4.uic.loadUi(uifile[, baseinstance=None[, package=']])

Load a Qt Designer .ui file and returns an instance of the userinterface.

Parameters:
  • uifile – the file name or file-like object containing the .ui file.
  • baseinstance – the optional instance of the Qt base class. If specified then theuser interface is created in it. Otherwise a new instance of the baseclass is automatically created.
  • package – the optional package that is the base package for any relative importsof custom widgets.
Return type:

the QWidget sub-class that implements the user interface.

pyuic4

The pyuic4 utility is a command line interface to theuic module. The command has the following syntax:

The full set of command line options is:

-h, --help

A help message is written to stdout.

--version

The version number is written to stdout.

-i <N>, --indent <N>

The Python code is generated using an indentation of <N> spaces. If<N> is 0 then a tab is used. The default is 4.

-o <FILE>, --output <FILE>

The Python code generated is written to the file <FILE>.

-p, --preview

The GUI is created dynamically and displayed. No Python code is generated.

-w, --pyqt3-wrapper

The generated Python code includes a small wrapper that allows the GUI tobe used in the same way as it is used in PyQt v3.

-x, --execute

The generated Python code includes a small amount of additional code thatcreates and displays the GUI when it is executes as a standaloneapplication.

--from-imports

Resource modules are imported using from.import rather than a simpleimport.

Note that code generated by pyuic4 is not guaranteed to becompatible with earlier versions of PyQt. However, it is guaranteed to becompatible with later versions. If you have no control over the version ofPyQt the users of your application are using then you should runpyuic4, or call compileUi(), as part of yourinstallation process. Another alternative would be to distribute the .uifiles (perhaps as part of a resource file) and have your application load themdynamically.

Writing Qt Designer Plugins¶

Designer

Pyqt Qt Designer Signals And Slots Video

Qt Designer can be extended by writing plugins. Normally this is done usingC++ but PyQt also allows you to write plugins in Python. Most of the time aplugin is used to expose a custom widget to Designer so that it appears inDesigner’s widget box just like any other widget. It is possibe to change thewidget’s properties and to connect its signals and slots.

It is also possible to add new functionality to Designer. See the Qtdocumentation for the full details. Here we will concentrate on describinghow to write custom widgets in Python.

The process of integrating Python custom widgets with Designer is very similarto that used with widget written using C++. However, there are particularissues that have to be addressed.

  • Designer needs to have a C++ plugin that conforms to the interface defined bythe QDesignerCustomWidgetInterface class. (If the plugin exposes morethan one custom widget then it must conform to the interface defined by theQDesignerCustomWidgetCollectionInterface class.) In addition the pluginclass must sub-class QObject as well as the interface class. PyQt doesnot allow Python classes to be sub-classed from more than one Qt class.
  • Designer can only connect Qt signals and slots. It has no understanding ofPython signals or callables.
  • Designer can only edit Qt properties that represent C++ types. It has nounderstanding of Python attributes or Python types.

PyQt provides the following components and features to resolve these issues assimply as possible.

  • PyQt’s QtDesigner module includes additional classes (all of which have aQPy prefix) that are already sub-classed from the necessary Qt classes.This avoids the need to sub-class from more than one Qt class in Python. Forexample, where a C++ custom widget plugin would sub-class from QObjectand QDesignerCustomWidgetInterface, a Python custom widget plugin wouldinstead sub-class from QPyDesignerCustomWidgetPlugin.

  • PyQt installs a C++ plugin in Designer’s plugin directory. It conforms tothe interface defined by the QDesignerCustomWidgetCollectionInterfaceclass. It searches a configurable set of directories looking for Pythonplugins that implement a class sub-classed fromQPyDesignerCustomWidgetPlugin. Each class that is found is instantiatedand the instance created is added to the custom widget collection.

    The PYQTDESIGNERPATH environment variable specifies the set ofdirectories to search for plugins. Directory names are separated by a pathseparator (a semi-colon on Windows and a colon on other platforms). If adirectory name is empty (ie. there are consecutive path separators or aleading or trailing path separator) then a set of default directories isautomatically inserted at that point. The default directories are thepython subdirectory of each directory that Designer searches for itsown plugins. If the environment variable is not set then only the defaultdirectories are searched. If a file’s basename does not end with pluginthen it is ignored.

  • A Python custom widget may define new Qt signals usingpyqtSignal().

  • A Python method may be defined as a new Qt slot by using thepyqtSlot() decorator.

  • A new Qt property may be defined using the pyqtProperty()function.

Note that the ability to define new Qt signals, slots and properties fromPython is potentially useful to plugins conforming to any plugin interface andnot just that used by Designer.

For a simple but complete and fully documented example of a custom widget thatdefines new Qt signals, slots and properties, and its plugin, look in theexamples/designer/plugins directory of the PyQt source package. Thewidgets subdirectory contains the pydemo.py custom widget andthe python subdirectory contains its pydemoplugin.py plugin.

Design multiple windows in designer

To jump, of course, there must be multiple windows, so we design another window in designer. When we click the login button in the main interface, we will jump to this window.
The method is the same. Drag the control, save it as a. ui file after it is designed, and then convert the. ui file to a. py file.

They are connected by signals and slots

What are signals, slots?
This is a feature of designer. The user will send a signal to guide the slot function to complete the corresponding action. Too abstract, for example.
The code for the main window looks like this.

The above statement to complete the window jump is as follows.

signal

Pyqt qt designer signals and slots videoPyqt designer signals and slots free

Pyqt Designer Signals And Slots Free

Slot function

So to complete the jump, we have to go through the following steps:

1. Add signals and slots

On the control where you want to add a signal, add a statement. For example, we add a signal to the login button with the object name as the pushButton to connect to the open() slot function, which is used to open a new window.

  • self: for UI_ Instantiation object of MainWindow
  • pushbutton: the object name of the login button
  • Click: signal means to send the signal to the slot function when the user clicks the login button
  • Slot and signal connection functions: connect
  • open: slot function, that is, after receiving the signal, the function is called.
  • Import: is the name of the new window, tiaozhuan.py .
    In addition, when opening a new window, we need to close the original login window. In the same way, add a signal on the login button.
Pyqt Designer Signals And Slots

signal

Slot function

It is important to note that the close() method must be called with the real instantiated object when closing the window. It can't be replaced by self.

2. Modify the called window

Two modifications are needed:

  • class Ui_MainWindow(QMainWindow): change the object to QMainWindow

  • def __init__(self): ා add initialization function super (UI)_ MainWindow,self).__ init__ () self.setupUi (self)

    Add initialization function to class

3. Run the main window
Directly run the main window, you can see the heart of the GUI!

Note: in this case, if you want to run the program, you have to add a file.
Because in the tiaozhuan.py In this window, we introduce three pictures. How to solve this problem, put the resource file in the tiaozhuan.py File in the same directory.
Resource file code link: (put a piece of words, the article is too long to send out... )
https://download.csdn.net/download/leidawangzi/13613277

How to get the resource file? Moving on to the next section, we'll learn how to add pictures to the control.

Bibliography: Python GUI design (PyQt5 from introduction to practice) - tomorrow Technology