In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use PyQt to create a professional-looking GUI". In daily operation, I believe many people have doubts about how to use PyQt to create a professional-looking GUI. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "how to use PyQt to create a professional-looking GUI." Next, please follow the editor to study!
PyQt's layout manager, layout managers, provides a user-friendly and efficient way to arrange graphical components or widgets on GUI. Properly arranging widgets will make your GUI application look more elegant and professional. Learning to do this effectively is a basic skill for you to develop and run GUI applications using Python and PyQt.
In this tutorial, you will learn:
What are the benefits of using PyQt's layout managers
How to use layout managers of PyQt to programmatically lay out widgets on GUI
How to choose the right layout manager for your GUI application
How to arrange widgets in main window-based and dialog-based applications
With this knowledge and skills, you can use Python and PyQt to create professional-looking GUI applications.
Lay out graphic elements on GUI
When creating graphical user interface (GUI) applications, a common problem is how to make graphical components (buttons, menus, toolbars, labels, etc.) be placed consistently on forms and windows. This process is called GUI layout (GUI layout,), which is an important step in creating a GUI application.
Previously, if you wanted to lay out graphics components or widgets on a window, you could use one of the following methods:
Determine and manually set the static size and location for each widget on the window.
Dynamically calculate and set the size and location of each widget.
The first approach is fairly straightforward, but at least has the following disadvantages:
Your windows will not be resized and may cause problems when displaying them at different screen resolutions.
Your tags may not support localization correctly because the length of a given text varies from language to language.
Your widgets will be displayed differently on different platforms, which makes it difficult to write multi-platform applications that look good.
The second method is more flexible. However, it also has its disadvantages:
You have to do a lot of manual calculations to determine the correct size and location of each widget.
You have to do some extra calculations to correctly respond to window resizing.
Every time you modify the window layout, you must redo all the calculations.
Even though you can still use either of these two methods to layout GUI, most of the time you probably want to use the third and more convenient method implemented by the most advanced GUI framework or toolkit: the layout manager layout managers. Note: in some GUI frameworks, such as Tkinter, the layout manager is also called geometry managers.
Layout managers automatically arranges widgets on GUI according to your specific needs. It avoids the compatibility shortcomings of the first method and the complex calculation of the second method.
In the following sections, you will learn about PyQt's built-in layout managers and how to use them to effectively lay out the graphical components of a GUI application.
Various forms of PyQt layout
In PyQt, widgets are graphical components that are used as building blocks for GUI applications. When you put a bunch of widgets on the window to create a GUI, you need to give them some order. You need to set the size and position of the widgets on the window, and you need to define their behavior when the user resizes the underlying window.
Note: there are some incomplete parts in the official documentation of PyQt5. To solve this problem, you can view the PyQt4 document, the Qt for Python document, or the original Qt document.
To arrange widgets on a window or form in PyQt, you can use the following techniques:
Use .resize () and .move () on the widget to provide absolute size and position.
Reimplement .resizeEvent () and dynamically calculate the size and location of the widget.
Use the layout manager and let them do all the calculations and hard work for you.
These techniques usually correspond to the three different methods for laying out GUI described in the previous section.
Again, it may be a good idea to calculate the size and location dynamically, but most of the time, it is better to use the layout manager. In PyQt, a layout manager is a class that provides the required functionality to automatically manage the size, location, and resizing behavior of small parts in a layout.
Using the layout manager, you can automatically arrange subassemblies within any parent assembly, container, or widget. Using the layout manager ensures that you make the most of the free space on the GUI and that the application is still available when the user resizes the window.
To add a widget to the layout manager when acting as a container for widgets and other layouts, call .addWidget () on the current layout. To add a layout to another layout, call .addLayout () on the current layout. You will learn more about nested layouts in the section "nesting layouts to build complex GUI".
After you have added all the necessary widgets to the layout manager, you can use .setLayout () to set the layout manager on the given widget. You can set the layout manager on any subclass of QWidget, including windows or forms.
Note: QMainWindow is a PyQt class that can be used to create main widow-style applications. This class has its own built-in layout manager. Therefore, if you are using QMainWindow, you usually do not need to set up a layout manager on the main window object.
All widgets in the layout are automatically set as children of the widget that installs the layout, not the layout itself. This is because widgets can only have other widgets (not layouts) as their parents.
PyQt's layout manager provides some cool features that make it easier for you to create beautiful GUI applications:
Handle the size and location of the widget without any calculation
When the user resizes the underlying window, the widget is resized and repositioned
Resize tags to better support internationalization
Provide native window layout for multi-platform applications
In the long run, using layout managers will also greatly increase your productivity and improve the maintainability of your code.
PyQt provides four common layout manager classes:
QHBoxLayout arranges widgets in a horizontal box.
QVBoxLayout arranges widgets in a vertical box.
QGridLayout arranges widgets in a grid.
QFormLayout arranges widgets in two columns.
In the next few sections, you will learn the basics of how to use these generic layout managers.
Use the common layout manager
When you use PyQt to create GUI applications, you typically use one or more of the four generic layouts you saw at the end of the previous section to place widgets on windows and forms.
In the next few sections, you will learn how to create and use four common layout managers with the help of some examples.
Build horizontal layout: QHBoxLayout
The space Box layout managers gets from the parent layout or widget is divided into multiple boxes or cells, and each widget in the layout is then filled with a box.
QHBoxLayout is one of two box layouts available in PyQt. This layout manager allows you to arrange widgets horizontally, one after another. These widgets are added to the layout from left to right. This means that the widget you first add to the code will be the leftmost widget in the layout.
To add a widget to a QHBoxLayout object, call .addWidget (widget,stretch,alignment) on the layout object. This method accepts one required parameter and two optional parameters:
Widget is a required parameter that holds the specific widget to be added to the layout.
Stretch is an optional parameter that contains an integer that represents the stretch factor to be applied to the widget. Widgets with higher stretch factors grow more when the window is resized. The default is 0, which means that the widget stretch factor is not assigned.
Alignment is an optional parameter that contains horizontal and vertical flags. You can combine these flags to produce the desired widget alignment within the cells they contain. The default is 0, which means that the widget will populate the entire cell.
Here is a small application that shows how to create a horizontal layout using QHBoxLayout. In this example, you will use the QPushButton object to better visualize where each widget is placed in the layout based on the order in which the widget was added to the code:
Import sys from PyQt5.QtWidgets import (QApplication, QHBoxLayout, QPushButton, QWidget ) class Window (QWidget): def _ init__ (self): super (). _ _ init__ () self.setWindowTitle ("QHBoxLayout Example") # Create a QHBoxLayout instance layout = QHBoxLayout () # Add widgets to the layout layout.addWidget (QPushButton ("Left-Most")) layout.addWidget (QPushButton ("Center") 1) layout.addWidget (QPushButton ("Right-Most"), 2) # Set the layout on the application's window self.setLayout (layout) print (self.children ()) if _ _ name__ = "_ _ main__": app = QApplication (sys.argv) window = Window () window.show () sys.exit (app.exec_ ())
On line 15, create a QHBoxLayout object called layout. In lines 17 to 19, use .addWidget () to add three buttons to the layout. Notice that you passed 1 and 2 to the stretch parameter in the Center and rightmost buttons, respectively. In line 21, use .setLayout () to set the layout to the top-level layout of the window.
If you run this application, you will see the following window on the screen:
The window contains three buttons arranged horizontally. Notice that the leftmost button corresponds to the first button you added in the code. Therefore, the order in which buttons are displayed is the same as the order in which you add buttons to your code (from left to right) (from top to bottom).
The Center and Rightmost buttons have different stretch factors, so they scale proportionally when the window is resized.
In addition, all buttons in the layout and the layout itself are set as children of Window. This is done automatically by the layout object, which calls .setParent () internally on each widget. The call to print () on line 17 will print a list of descendants of Window on your terminal to prove this behavior.
Build a vertical layout: QVBoxLayout
QVBoxLayout arranges widgets vertically, one below the other. You can use this class to create a vertical layout and arrange widgets from top to bottom. Because QVBoxLayout is another box layout, its .addWidget () method works the same way as in QHBoxLayout.
Here is a PyQt application that shows how to create and use QVBoxLayout objects to create a vertical arrangement of widgets in GUI:
Import sys from PyQt5.QtWidgets import (QApplication, QPushButton, QVBoxLayout, QWidget,) class Window (QWidget): def _ _ init__ (self): super (). _ init__ () self.setWindowTitle ("QVBoxLayout Example") self.resize ) # Create a QVBoxLayout instance layout = QVBoxLayout () # Add widgets to the layout layout.addWidget (QPushButton ("Top")) layout.addWidget (QPushButton ("Center")) layout.addWidget (QPushButton ("Bottom")) # Set the layout on the application's window self.setLayout (layout) if _ _ name__ = = "_ main__": App = QApplication (sys.argv) window = Window () window.show () sys.exit (app.exec_ ())
On line 16, you will create an instance of QVBoxLayout. On lines 18 to 20, add three buttons to the layout. Finally, set the layout to the top-level layout of the window.
If you run this application, the following window is displayed:
Your window displays three buttons arranged vertically, one under the other. These buttons are displayed in the same order (from top to bottom) as you added to the code (from top to bottom).
Arrange widgets in the grid: QGridLayout
You can use QGridLayout to arrange widgets in a grid of rows and columns. Each widget will have a relative position in the grid. To define the location of the widget or the cells in the grid, use a pair of coordinates of the table (rows, columns). These coordinates should be zero-based integers.
QGridLayout takes up the available space of its parent, divides it into rows and columns, and then places each widget in its own cell or box. QGridLayout automatically calculates how many rows and columns the final layout will contain based on the number of widgets and their coordinates. If you do not add a widget to a given cell, QGridLayout will make the cell empty.
To add a widget to a grid layout, call .addWidget () on the layout. This method has two different overloaded implementations:
AddWidget (widget, row, column, alignment) adds widget to the cell of (row, column).
AddWidget (widget,fromRow,fromColumn,rowSpan,columnSpan,alignment) adds widget to the cell, spanning multiple rows, columns, or both.
The first implementation takes the following parameters:
Widget is a required parameter to hold the specific widgets you need to add to the layout.
Row is a required parameter that contains an integer that represents the coordinates of the rows in the grid.
Column is a required parameter that contains an integer that represents the coordinates of the columns in the grid.
Alignment is an optional parameter that saves the alignment of the widget within the cells it contains. The default is 0, which means that the widget will populate the entire cell.
This is an example of how to create a widget grid using QGridLayout:
Import sys from PyQt5.QtWidgets import (QApplication, QGridLayout, QPushButton, QWidget,) class Window (QWidget): def _ _ init__ (self): super (). _ init__ () self.setWindowTitle ("QGridLayout Example") # Create a QGridLayout instance layout = QGridLayout () # Add widgets to the layout layout.addWidget (QPushButton ("Button at (0,0)") 0,0) layout.addWidget (QPushButton ("Button at (0,1)"), 0,1) layout.addWidget (QPushButton ("Button at (0,2)"), 0,2) layout.addWidget (QPushButton ("Button at (1,0)"), 1,0) layout.addWidget (QPushButton ("Button at (1,1)"), 1,1) layout.addWidget (QPushButton ("Button at (1,2)"), 1 2) layout.addWidget (QPushButton ("Button at (2,0)"), 2,0) layout.addWidget (QPushButton ("Button at (2,1)"), 2,1) layout.addWidget (QPushButton ("Button at (2,2)"), 2 2) # Set the layout on the application's window self.setLayout (layout) if _ _ name__ = "_ _ main__": app = QApplication (sys.argv) window = Window () window.show () sys.exit (app.exec_ ())
On line 15, create the QGridLayout object. Then, on lines 17 to 25, use .addWidget () to add the widget to the layout. To see how a grid layout with no assigned widgets manages cells, comment out one or more of the rows, and then run the application again.
If you run this code from the command line, you will get a window like this:
Each widget in the QGridLayout object occupies the cell defined by the pair of coordinates you provided in .addWidget (). The text on each button reflects these coordinates. The coordinates are zero-based, so the first cell is located in (0pc0).
In the second implementation of .addWidget (), the widget and alignment parameters remain the same, and you have four other parameters that you can use to place the widget in multiple rows or columns:
FromRow assigns an integer that represents the row in which the widget will start.
FromColumn assigns an integer that represents the column in which the widget will start.
RowSpan assigns an integer that represents the number of rows the widget will occupy in the grid.
ColumnSpan assigns an integer that represents the number of columns the widget will occupy in the grid.
This is an application that shows how the .addWidget () variant works:
Import sys from PyQt5.QtWidgets import (QApplication, QGridLayout, QPushButton, QWidget,) class Window (QWidget): def _ _ init__ (self): super (). _ init__ () self.setWindowTitle ("QGridLayout Example") # Create a QGridLayout instance layout = QGridLayout () # Add widgets to the layout layout.addWidget (QPushButton ("Button at (0,0)"), 0 0) layout.addWidget (QPushButton ("Button at (0,1)"), 0,1) layout.addWidget (QPushButton ("Button Spans two Cols"), 1,0,1 2) # Set the layout on the application's window self.setLayout (layout) if _ _ name__ = "_ _ main__": app = QApplication (sys.argv) window = Window () window.show () sys.exit (app.exec_ ())
In line 19, use the second implementation of .addWidget () to add a button that occupies two columns in the grid. The button starts with the second row (fromRow = 1) and the first column (fromColumn = 0). Finally, the button occupies one row (rowSpan = 1) and two columns (columnSpan = 2).
If you run this application, you will see the following window on the screen:
In this layout, you can make a widget occupy multiple cells, just like using a "across two columns" button.
At this point, the study on "how to use PyQt to create a professional-looking GUI" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.