Pyqt5.files.wordpress.com



Your first GUI app with Python and PyQtIntroductionMany people struggle with learning how to build a GUI app. The most common reason is, they don’t even know where to start. Most tutorials are purely text based, and it’s hard to learn GUI development using text, since GUIs are mainly a visual medium.We will get around that by building a simple GUI app, and show you how easy it is to get started. Once you understand the basics, it’s easy to add advanced stuff.This is what we will be building:A simple GUI app that takes in a price, a tax rate and calculates the final price.Most tutorials on GUI apps try to layout the GUI blocks using code, but that is very painful to do. We will be using the superb QT Designer tool to layout our app:So no struggling laying out the design by hand. Everything will be done graphically.All the source code is here.Pre-requisitesIf you followed my advice and installed Anaconda, you will already have PyQt4. If not, you will need to get it from here.You also need Qt Designer.Update: As Steve points out in the comments, Anaconda comes with qt-designer, so you don’t need to download anything! It is in: …\Anaconda3\Library\bin and is called designer-qt4.exe.I recommend you download the whole QT suite, as there are some other useful tools in there too.Getting StartedNote: You can click on any image below to see the full size, in case you want more detail.Start QT Designer. In the window that comes up, choose Main Window, as it will give is a blank canvas:?The next thing to do is to select the Text Edit box on the left:?Drag Text Edit to the main window, to get a box like:?See the right side, where I have clumsily red circled a box? That is where the name of the object is. The name is the way this object will be called from our Python code, so call it something sensible.?I’m calling it price_box, as we will enter the price into this box. The next thing we will do is attach a label to the box, to make it clear to the user what this box is for.Above, I have circled the label. Drag it across to the main window.?It gets the default text of TextLabel. Double click it and change it to Price. You can also make the text large and bold, as seen here:For the tax box, we are going to use something different. See the spin box:?The circle on the left is a spin box. This limits the values you can enter. We don’t need a spinbox, it’s just good to see how you can use different widgets that QT Creator provides. Drag the?spin box to the window. The first thing we do is change the objectName to something sensible, tax_rate in our case. Remember, this is how this object will be called from Python.We can choose a default value for our spinbox. I’m choosing 20:If you look at the image above, you can also set the minimum and maximum limits. We will keep them to what they are.We will also add another label called Tax Rate, same as we did before. Also look at the circled Push Button we will be using next:?Now, select the Push Button box and drag it to our window.The button just says PushButton, which isn’t very helpful. By now, you should know how to change this. But before that, we change the name of the button (and not the text) to calc_tax_button.Next,? we change the actual text:Drag another Text Edit box on to the window. You don’t need to label it, as we will print the output in here. Do change it’s name to results_window (not shown below, but you should know how to do it by now).If you want, you can add a header. This is a simple label box with the font increased:And save your work:This file will be used in the next part when we write the code, so store it somewhere you can access it.This file that we? created is just a XML file. Open it in a text editor, if you want, and you will find something like this:Writing the codeQt’s code is object oriented, and in? a manner that is easy to follow. Each of the widgets we added is an object, with it’s own functions like toPlainText() (to read the value in a box). This makes it quite easy to use.I’m sure the official documentation mentions this somewhere, but you have to do some setup before you can use the code. I couldn’t find this setup anywhere, so I worked back from the official examples (as well as other online tutorials) to find the smallest program you need to initialize the class. I have checked this function in as pyqt_skeleton.py.This is useful, as everytime you start a new PyQt project, use this skeleton to start off, and add your code.The code is:123456789101112131415161718import sysfrom PyQt4 import QtCore, QtGui, uic?qtCreatorFile = "" # Enter file here.?Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)?class MyApp(QtGui.QMainWindow, Ui_MainWindow):????def __init__(self):????????QtGui.QMainWindow.__init__(self)????????Ui_MainWindow.__init__(self)????????self.setupUi(self)?if __name__ == "__main__":????app = QtGui.QApplication(sys.argv)????window = MyApp()????window.show()????sys.exit(app.exec_())The main thing to note is line 3:1qtCreatorFile = "" # Enter file here.This is where you add the file you created earlier. It is loaded using the inbuilt function:1Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)?Let’s take a quick look at the code:12345if __name__ == "__main__":????app = QtGui.QApplication(sys.argv)????window = MyApp()????window.show()????sys.exit(app.exec_())The main code creates a new Qt Gui application. Passing in sys.argv is required, as QT can be configured from the command line. We won’t be doing that.Finally, we create a class called MyApp, which inherits from Qt libraries and initializes the parent classes:12345class MyApp(QtGui.QMainWindow, Ui_MainWindow):????def __init__(self):????????QtGui.QMainWindow.__init__(self)????????Ui_MainWindow.__init__(self)????????self.setupUi(self)You don’t need to know the details of this code. Just use the skeleton and work on that.Take this file, pyqt_skeleton.py, and rename it to pyqt_first.py. That’s because we don’t want to edit the original file.The first thing to do is add our XML file, the one that contains our GUI, to the code. Replace this line:1qtCreatorFile = "" # Enter file here.with1qtCreatorFile =??"tax_calc.ui"This will load our GUI file into memory. Now, the key widget in our GUI was the button. Once you press the button, something happens. What? We need to tell our code what to do when the user presses the Calculate Tax button. In the __init__ function, add this line:1self.calc_tax_button.clicked.connect(self.CalculateTax)What does this do? Remember we called our button calc_tax_button? (This was the name of the object, not the text that was displayed on it.) clicked is an internal function that is called when (surprise) someone clicks on the button. All QT widgets have specific functions, which you can find our by Googling. The last part of the code says connect(self.CalculateTax). This says that connect this button to a function called self.CalculateTax, so that everytime the user presses this button, that function is called.We haven’t written that function yet. Let’s do it now.In the MyApp Class, add another function. We will look at the whole function first, and then go into details:123456????def CalculateTax(self):????????price = int(self.price_lainText())????????tax = (self.tax_rate.value())????????total_price = price??+ ((tax / 100) * price)????????total_price_string = "The total price with tax is: " + str(total_price)????????self.results_window.setText(total_price_string)Okay, let’s look at the code above line by line.We have to do two things: Read the price box, read the tax box, and calculate the final price. Let’s do that now. Remember, we will call the objects by the names we gave them (which is why I asked you not to use the default generic names like box1, as that would have been confusing pretty soon).1price = int(self.price_lainText())We read our price_box. toPlainText() is an internal function that reads the value stored in that box. You don’t have to remember all these functions, by the way. I just Google something like “Qt Textbox read data” to find out what the name of the function is, though you will start to remember the names after some time, as they are very logically named.The read value is a string, so we convert it to an integer and store it in a variable called price.Next, we read the tax box:1tax = (self.tax_rate.value())Again, value() is the function for reading from a spinbox. Thanks, Google.Now that we have both these values, we can calculate the final price using very high tech maths:12total_price = price??+ ((tax / 100) * price)total_price_string = "The total price with tax is: " + str(total_price)We create a string with our final price. This is because we will output this string directly to our app:1self.results_window.setText(total_price_string)In our results_window, we call the function setText(), which outputs the string we created.Just run the file using:1python pyqt_first.pyAnd there you go. A simple introduction to PyQt.If you want more fun, trying playing with the different widgets, though be warned, you can add too many widgets and make your app confusing to use.Are you interested in seeing more on this? If so, please leave a comment, or contact me.89 thoughts on “Your first GUI app with Python and PyQt” Andre says: March 19, 2015 at 8:23 pm HiVery interesting tool as Python always lacked a good GUI. Wonder whether this will work on a Raspberry Pi platform?RegardsAndreReplyShantnu says: March 20, 2015 at 3:01 pm Hi Andre,In theory yes, but I have never tried it.ReplyNelson says: December 19, 2015 at 1:24 pm Hi Andre, just tested the code on a RPi2B. It works perfect. Regards,NelsonReplyJohn Haddy says: March 20, 2015 at 5:57 am I note that Qt is now at revision 5. Is PyQt4 still recommended (over PyQt5)?ReplyShantnu says: March 20, 2015 at 3:02 pm QT5 is the shinier newer version. Unfortunately, it breaks backward compatibility.I chose PYQy4 merely because it came with my install of Anaconda.ReplyLemay says: April 14, 2015 at 6:38 pm Hi Shantnu,Awesome guide, really helped me out. Thanks for posting!I’m a Mechanical Engineer using Qt Designer alongside PySide to develop engineering analysis applications. I would love for some more tutorials on using Qt Designer and its implementation through PySide (or Qt). Specifically, I’m trying to implement plots from matplotlib into a GUI designed using Qt designer.Any more tutorials/help on this subject matter would be greatly appreciated!Thanks so much!-Lemay ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download