Skip to content Skip to sidebar Skip to footer

Keep Button Flat Until Pressed Again Pyqt

In this tutorial we'll acquire how to utilize PyQt to create desktop applications with Python. Get-go we'll create a series of simple windows on your desktop to ensure that PyQt is working and innovate some of the bones concepts. And so we'll take a brief look at the event loop and how it relates to GUI programming in Python. Finally we'll expect at Qt'due south QMainWindow which offers some useful mutual interface elements such as toolbars and menus. These will be explored in more item in the subsequent tutorials.

Creating an application

Let's create our first application! To first create a new Python file — you tin phone call it whatever you like (due east.one thousand. app.py) and save it somewhere attainable. We'll write our simple app in this file.

We'll exist editing inside this file as we continue, and you may want to come dorsum to earlier versions of your code, and then remember to keep regular backups.

The source lawmaking for the application is shown below. Type information technology in verbatim, and be careful not to make mistakes. If you do mess up, Python will let you know what's wrong.

python

            from PyQt5.QtWidgets import QApplication, QWidget  # Only needed for access to control line arguments import sys  # You need ane (and only one) QApplication example per application. # Pass in sys.argv to allow command line arguments for your app. # If you know yous won't use command line arguments QApplication([]) works too. app = QApplication(sys.argv)  # Create a Qt widget, which will be our window. window = QWidget() window.show()  # Important!!!!! Windows are hidden by default.  # Start the upshot loop. app.exec()   # Your awarding won't reach hither until you lot exit and the event # loop has stopped.                      

First, launch your application. Yous can run information technology from the command line like any other Python script, for example --

Run information technology! You will now come across your window. Qt automatically creates a window with the normal window decorations and you tin can drag it effectually and resize information technology like whatever window.

What you'll see will depend on what platform you're running this example on. The epitome beneath shows the window as displayed on Windows, macOS and Linux (Ubuntu).

Our window, as seen on Windows, macOS and Linux. Our window, as seen on Windows, macOS and Linux.

Stepping through the code

Permit's step through the code line by line, so nosotros empathize exactly what is happening.

First, we import the PyQt classes that we demand for the awarding. Here nosotros're importing QApplication, the application handler and QWidget, a basic empty GUI widget, both from the QtWidgets module.

python

            from PyQt5.QtWidgets import QApplication, QWidget                      

The main modules for Qt are QtWidgets, QtGui and QtCore.

Y'all could exercise from <module> import * but this kind of global import is generally frowned upon in Python, then we'll avert it hither.

Side by side nosotros create an example of QApplication, passing in sys.arg, which is Python listing containing the command line arguments passed to the application.

python

            app = QApplication(sys.argv)                      

If yous know you won't be using control line arguments to command Qt you can pass in an empty list instead, due east.g.

python

            app = QApplication([])                      

Next nosotros create an instance of a QWidget using the variable name window.

python

            window = QWidget() window.prove()                      

In Qt all top level widgets are windows -- that is, they don't have a parent and are not nested inside some other widget or layout. This means y'all tin can technically create a window using whatsoever widget you like.

Widgets without a parent are invisible by default. So, later creating the window object, we must always call .show() to go far visible. You can remove the .show() and run the app, but you'll have no style to quit it!

What is a window? - Holds the user-interface of your application - Every awarding needs at least one (...but can have more) - Application will (by default) get out when last window is closed

Finally, nosotros phone call app.exec() to offset upwardly the event loop.

In PyQt5 you can also employ app.exec_(). This was a legacy feature avert a clash with the exec reserved give-and-take in Python 2.

What's the event loop?

Earlier getting the window on the screen, at that place are a few fundamental concepts to introduce about how applications are organized in the Qt globe. If you're already familiar with upshot loops you tin safely skip to the next section.

The cadre of every Qt Applications is the QApplication course. Every awarding needs i — and only 1 — QApplication object to function. This object holds the event loop of your application — the core loop which governs all user interaction with the GUI.

The event loop in Qt.

Each interaction with your awarding — whether a press of a cardinal, click of a mouse, or mouse motion — generates an result which is placed on the event queue. In the event loop, the queue is checked on each iteration and if a waiting issue is found, the event and command is passed to the specific event handler for the effect. The event handler deals with the event, and so passes command dorsum to the upshot loop to wait for more than events. In that location is only 1 running event loop per application.

The QApplication class - QApplication holds the Qt outcome loop - One QApplication instance required - Y'all application sits waiting in the issue loop until an action is taken - There is only one event loop running at any fourth dimension

Downloadable ebook (PDF, ePub) & Complete Source lawmaking

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!

For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the lawmaking [[ couponCode ]] — Enjoy!

QMainWindow

As we discovered in the last part, in Qt any widgets can be windows. For example, if you lot replace QtWidget with QPushButton. In the example below, you lot would get a window with a single push-able button in it.

python

            import sys from PyQt5.QtWidgets import QApplication, QPushButton  app = QApplication(sys.argv)  window = QPushButton("Button Me") window.show()  app.exec()                      

This is nifty, but not really very useful -- it'due south rare that y'all need a UI that consists of only a single command! Only, as we'll discover afterwards, the ability to nest widgets within other widgets using layouts means yous can construct circuitous UIs within an empty QWidget.

Simply, Qt already has a solution for you -- the QMainWindow. This is a pre-made widget which provides a lot of standard window features yous'll make use of in your apps, including toolbars, menus, a statusbar, dockable widgets and more. We'll look at these avant-garde features afterward, but for now, we'll add a simple empty QMainWindow to our application.

python

            import sys from PyQt5.QtWidgets import QApplication, QMainWindow  app = QApplication(sys.argv)  window = QMainWindow() window.show()  # Beginning the event loop. app.exec()                      

Run it! Y'all will at present encounter your main window. It looks exactly the same as before!

So our QMainWindow isn't very interesting at the moment. We can ready that by calculation some content. If you want to create a custom window, the all-time approach is to subclass QMainWindow and so include the setup for the window in the __init__ block. This allows the window beliefs to be self independent. We can add together our own subclass of QMainWindow — call it MainWindow to keep things simple.

python

            import sys  from PyQt5.QtCore import QSize, Qt from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton   # Bracket QMainWindow to customize your application's primary window grade MainWindow(QMainWindow):     def __init__(cocky):         super().__init__()          self.setWindowTitle("My App")         push button = QPushButton("Press Me!")          # Ready the fundamental widget of the Window.         self.setCentralWidget(button)   app = QApplication(sys.argv)  window = MainWindow() window.show()  app.exec()                      

For this demo we're using a QPushButton. The core Qt widgets are always imported from the QtWidgets namespace, equally are the QMainWindow and QApplication classes. When using QMainWindow we employ .setCentralWidget to place a widget (here a QPushButton) in the QMainWindow -- by default it takes the whole of the window. Nosotros'll look at how to add multiple widgets to windows in the layouts tutorial.

When yous subclass a Qt form yous must always call the super __init__ function to allow Qt to set up the object.

In our __init__ cake nosotros first use .setWindowTitle() to change the title of our principal window. Then we add our first widget — a QPushButton — to the centre of the window. This is one of the basic widgets available in Qt. When creating the push button you can pass in the text that you want the button to brandish.

Finally, we call .setCentralWidget() on the window. This is a QMainWindow specific function that allows you to set the widget that goes in the middle of the window.

Run it! You volition now see your window again, merely this fourth dimension with the QPushButton widget in the middle. Pressing the push button will do zilch, we'll sort that adjacent.

Our QMainWindow with a single QPushButton on Windows, macOS and Linux. Our QMainWindow with a unmarried QPushButton on Windows, macOS and Linux.

Nosotros'll cover more widgets in detail soon simply if you lot're impatient and would like to jump ahead you tin have a look at the http://doc.qt.io/qt-5/widget-classes.html#basic-widget-classes[QWidget documentation]. Effort calculation the different widgets to your window!

The window is currently freely resizable -- if you catch any corner with your mouse you can drag and resize it to any size you want. While it's good to let your users resize your applications, sometimes y'all may desire to place restrictions on minimum or maximum sizes, or lock a window to a stock-still size.

In Qt sizes are defined using a QSize object. This accepts width and height parameters in that order. For instance, the following will create a fixed size window of 400x300 pixels.

python

            import sys  from PyQt5.QtCore import QSize, Qt from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton   # Bracket QMainWindow to customize your application's main window class MainWindow(QMainWindow):     def __init__(self):         super().__init__()          self.setWindowTitle("My App")          button = QPushButton("Press Me!")          self.setFixedSize(QSize(400, 300))          # Gear up the central widget of the Window.         self.setCentralWidget(push)   app = QApplication(sys.argv)  window = MainWindow() window.testify()  app.exec()                      

Run it! You will see a stock-still size window -- effort and resize it, it won't piece of work.

Our fixed-size window, notice that the _maximize_ control is disabled on Windows & Linux. On macOS you _can_ maximize the app to fill the screen, but the central widget will not resize. Our fixed-size window, notice that the _maximize command is disabled on Windows & Linux. On macOS you can maximize the app to fill the screen, but the cardinal widget will not resize._

Likewise as .setFixedSize() you can also call .setMinimumSize() and .setMaximumSize() to prepare the minimum and maximum sizes respectively. Experiment with this yourself!

You tin can use these size methods on any widget.

In this section we've covered the QApplication class, the QMainWindow class, the event loop and experimented with adding a simple widget to a window. In the next department we'll take a look at the mechanisms Qt provides for widgets and windows to communicate with one some other and your ain code.

fieldwastone.blogspot.com

Source: https://www.pythonguis.com/tutorials/creating-your-first-pyqt-window/

Post a Comment for "Keep Button Flat Until Pressed Again Pyqt"