Difference between revisions of "PyQt5 Simple Example"

From dftwiki3
Jump to: navigation, search
Line 5: Line 5:
 
</bluebox>
 
</bluebox>
  
 +
<br />
 +
=Environment=
 +
<br />
 +
* Mac OSX Sierra
 +
* Qt5.10.1, with Qt Creator 4.6.2 (Clang 8.0 (Apple), 64 bits)
 +
* Python 3.5
 
<br />
 
<br />
 
=The GUI=
 
=The GUI=
Line 251: Line 257:
 
=PyQt5=
 
=PyQt5=
 
<br />
 
<br />
* Convert the .ui file to a Python .py file:
+
==Generating the Python version of the UI file==
 +
<br />
 +
* Convert the .ui file to a Python .py file.  Open a Terminal window and type the following command:
 
   
 
   
 
  pyuic5 -x  mainwindow.ui -o mainwindow.py
 
  pyuic5 -x  mainwindow.ui -o mainwindow.py
Line 260: Line 268:
 
   
 
   
 
: You should see the GUI as illustrated above.  Flip between the two tabs to verify that both have been populated.
 
: You should see the GUI as illustrated above.  Flip between the two tabs to verify that both have been populated.
 +
<br />
 +
==Edit the mainwindow.py File==
 +
<br />
 +
There are few edits you need to make to the mainwindow.py file, illustrated with the '''diff''' output below, between the original (on the right) and the edited version (on the left).  We omitted many lines that were identical in both versions.  Just concentrate on the lines that have a "&lt;" or "|" sign in the middle of the two columns.
 +
 +
::<source lang="text">
 +
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
 +
 +
# Form implementation generated from reading ui file 'mainwin # Form implementation generated from reading ui file 'mainwin
 +
# #
 +
# Created by: PyQt5 UI code generator 5.10.1 # Created by: PyQt5 UI code generator 5.10.1
 +
# #
 +
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
 +
 +
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5 import QtCore, QtGui, QtWidgets
 +
from PyQt5.QtCore import QObject, pyqtSlot       <
 +
 +
class Ui_MainWindow( QObject):       | class Ui_MainWindow(object):
 +
    def setupUi(self, MainWindow):     def setupUi(self, MainWindow):
 +
        MainWindow.setObjectName("MainWindow")         MainWindow.setObjectName("MainWindow")
 +
        MainWindow.resize(482, 600)         MainWindow.resize(482, 600)
 +
 +
(several lines skipped...)
 +
 +
        self.retranslateUi(MainWindow)         self.retranslateUi(MainWindow)
 +
        self.tabWidget.setCurrentIndex(1)         self.tabWidget.setCurrentIndex(1)
 +
        self.clearButton.clicked.connect(self.EAXlineEdit.cle         self.clearButton.clicked.connect(self.EAXlineEdit.cle
 +
        self.pushButton_2.clicked.connect( self.addRandomText |         self.pushButton_2.clicked.connect(MainWindow.addRando
 +
        self.pushButton.clicked.connect(self.textEdit.clear)         self.pushButton.clicked.connect(self.textEdit.clear)
 +
        QtCore.QMetaObject.connectSlotsByName(MainWindow)         QtCore.QMetaObject.connectSlotsByName(MainWindow)
 +
 +
    @pyqtSlot( )       <
 +
    def addRandomTextSlot( self ):       <
 +
        self.textEdit.insertPlainText( "Hello World!" )       <
 +
 +
if __name__ == "__main__": if __name__ == "__main__":
 +
    import sys     import sys
 +
   
 +
(several lines skipped)
 +
</source>

Revision as of 11:09, 13 June 2018

D. Thiebaut (talk) 11:46, 13 June 2018 (EDT)


In this tutorial we create a GUI with Qt5's designer, take the ui file resulting from it, convert it to a py file with the pyuic5 utility, and add a custom slot associated with the clicked signal of one of the push-buttons.


Environment


  • Mac OSX Sierra
  • Qt5.10.1, with Qt Creator 4.6.2 (Clang 8.0 (Apple), 64 bits)
  • Python 3.5


The GUI


We assume that you are familiar with creating a Qt5 GUI with Designer. If not, check out this tutorial which will take you through the required steps. The tutorial assumes Qt4, but should translate easily to Qt5.

Generating the GUI


  • Open Qt5
  • Create a New Project
  • Pick Qt for the type of project
  • Pick Qt Designer Form
  • Pick Main Window as a template
  • Accept mainwindow.ui as the name of the file
  • Click Done
  • Follow steps similar to those illustrated in this tutorial to create a main window with 2 tabs.
  • First tab: label, line edit, push-button labeled Clear
  • Second tab: textEdit, two push-buttons, labeled "Clear" and "Random Text"
  • Edit signals and slots to create these connections
  • On Tab 1, connect "clicked" signal of Clear push-button to clear() method of LineEdit widget
  • On Tab 2, connect "clicked" signal of Clear push-button to clear() method of TextEdit widget
  • ON Tab 2, connect "clicked" signal of Random Text push-button to a new slot called addRandomTextSlot() belonging to the main window.


The GUI with the two tabs


The Main Window GUI is shown below. It contins a TAB widget with two tabs, both shown.

PyQt5GUI 2Tabs.png


The UI File


Once the GUI is created in Designer, save it to mainwindow.ui, shown below for reference.

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>482</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="0">
     <widget class="QTabWidget" name="tabWidget">
      <property name="currentIndex">
       <number>1</number>
      </property>
      <widget class="QWidget" name="tab">
       <attribute name="title">
        <string>Processor</string>
       </attribute>
       <layout class="QGridLayout" name="gridLayout_2">
        <item row="0" column="0">
         <layout class="QHBoxLayout" name="horizontalLayout">
          <item>
           <widget class="QPushButton" name="clearButton">
            <property name="text">
             <string>Clear</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLineEdit" name="EAXlineEdit"/>
          </item>
          <item>
           <widget class="QLabel" name="label">
            <property name="text">
             <string>EAX</string>
            </property>
           </widget>
          </item>
          <item>
           <spacer name="horizontalSpacer">
            <property name="orientation">
             <enum>Qt::Horizontal</enum>
            </property>
            <property name="sizeHint" stdset="0">
             <size>
              <width>40</width>
              <height>20</height>
             </size>
            </property>
           </spacer>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
      <widget class="QWidget" name="tab_2">
       <attribute name="title">
        <string>Memory</string>
       </attribute>
       <layout class="QGridLayout" name="gridLayout_4">
        <item row="0" column="0">
         <widget class="QTextEdit" name="textEdit"/>
        </item>
        <item row="1" column="0">
         <layout class="QGridLayout" name="gridLayout_3">
          <item row="0" column="0">
           <layout class="QHBoxLayout" name="horizontalLayout_2">
            <item>
             <widget class="QPushButton" name="pushButton">
              <property name="text">
               <string>Clear</string>
              </property>
             </widget>
            </item>
            <item>
             <spacer name="horizontalSpacer_2">
              <property name="orientation">
               <enum>Qt::Horizontal</enum>
              </property>
              <property name="sizeHint" stdset="0">
               <size>
                <width>40</width>
                <height>20</height>
               </size>
              </property>
             </spacer>
            </item>
            <item>
             <widget class="QPushButton" name="pushButton_2">
              <property name="text">
               <string>Random Text</string>
              </property>
             </widget>
            </item>
           </layout>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>482</width>
     <height>22</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="title">
     <string>File</string>
    </property>
    <addaction name="actionSave_Program"/>
    <addaction name="actionLoad_Program"/>
   </widget>
   <widget class="QMenu" name="menuQuit">
    <property name="title">
     <string>Quit</string>
    </property>
   </widget>
   <widget class="QMenu" name="menuHelp">
    <property name="title">
     <string>Help</string>
    </property>
   </widget>
   <addaction name="menuFile"/>
   <addaction name="menuQuit"/>
   <addaction name="menuHelp"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <action name="actionSave_Program">
   <property name="text">
    <string>Save Program</string>
   </property>
  </action>
  <action name="actionLoad_Program">
   <property name="text">
    <string>Load Program</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>clearButton</sender>
   <signal>clicked()</signal>
   <receiver>EAXlineEdit</receiver>
   <slot>clear()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>71</x>
     <y>301</y>
    </hint>
    <hint type="destinationlabel">
     <x>192</x>
     <y>299</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>pushButton_2</sender>
   <signal>clicked()</signal>
   <receiver>MainWindow</receiver>
   <slot>addRandomTextSlot()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>363</x>
     <y>521</y>
    </hint>
    <hint type="destinationlabel">
     <x>476</x>
     <y>440</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>pushButton</sender>
   <signal>clicked()</signal>
   <receiver>textEdit</receiver>
   <slot>clear()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>78</x>
     <y>521</y>
    </hint>
    <hint type="destinationlabel">
     <x>92</x>
     <y>449</y>
    </hint>
   </hints>
  </connection>
 </connections>
 <slots>
  <slot>addRandomTextSlot()</slot>
 </slots>
</ui>


PyQt5


Generating the Python version of the UI file


  • Convert the .ui file to a Python .py file. Open a Terminal window and type the following command:
pyuic5 -x  mainwindow.ui -o mainwindow.py

the -x option creates a main section to the mainwindow.py file that will allow us to test quickly whether the GUI looks as we intended. Try running the newly created file with Python 3:
python3 mainwindow.py

You should see the GUI as illustrated above. Flip between the two tabs to verify that both have been populated.


Edit the mainwindow.py File


There are few edits you need to make to the mainwindow.py file, illustrated with the diff output below, between the original (on the right) and the edited version (on the left). We omitted many lines that were identical in both versions. Just concentrate on the lines that have a "<" or "|" sign in the middle of the two columns.

# -*- coding: utf-8 -*-						# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainwin	# Form implementation generated from reading ui file 'mainwin
#								#
# Created by: PyQt5 UI code generator 5.10.1			# Created by: PyQt5 UI code generator 5.10.1
#								#
# WARNING! All changes made in this file will be lost!		# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets			from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSlot		      <

class Ui_MainWindow( QObject):				      |	class Ui_MainWindow(object):
    def setupUi(self, MainWindow):				    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")			        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(482, 600)				        MainWindow.resize(482, 600)

(several lines skipped...)

        self.retranslateUi(MainWindow)				        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(1)			        self.tabWidget.setCurrentIndex(1)
        self.clearButton.clicked.connect(self.EAXlineEdit.cle	        self.clearButton.clicked.connect(self.EAXlineEdit.cle
        self.pushButton_2.clicked.connect( self.addRandomText |	        self.pushButton_2.clicked.connect(MainWindow.addRando
        self.pushButton.clicked.connect(self.textEdit.clear)	        self.pushButton.clicked.connect(self.textEdit.clear)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)	        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    @pyqtSlot( )					      <
    def addRandomTextSlot( self ):			      <
        self.textEdit.insertPlainText( "Hello World!" )	      <

if __name__ == "__main__":					if __name__ == "__main__":
    import sys							    import sys
    
(several lines skipped)