PyQt5 - QApplication
QApplication 类管理 GUI 应用程序的控制流和主要设置。它专门研究 QGuiApplication 和基于 QWidget 的应用程序所需的一些功能。它处理特定于小部件的初始化、完成。对于任何使用 Qt 的 GUI 应用程序,无论在任何给定时间应用程序是否有 0、1、2 或更多窗口,都只有一个 QApplication 对象。对于非基于 QWidget 的 Qt 应用程序,请改用 QGuiApplication,因为它不依赖于 QtWidgets 库。
然后我们创建一个窗口实例并使用 sys.exit(App.exec()) 命令在事件循环中执行 QApplication 对象,下面是一些与 QApplication 对象一起使用的有用且经常使用的方法和属性。
Syntax: App = QApplication(sys.argv)
Parameters:
- beep: Sounds the bell, using the default volume and sound. This function is not available in Qt for Embedded Linux
- setFont: It sets the default font of the PyQt5 Application
- aboutQt: Displays a simple message box about Qt. The message includes the version number of Qt being used by the application.
- closeAllWindows: Closes all top-level windows. This function is particularly useful for applications with many top-level windows.
- setAutoSipEnabled: It automatically displays the SIP when entering widgets that accept keyboard input
- setCursorFlashTime: This method sets the text cursor’s flash (blink) time in milliseconds
- setDoubleClickInterval: This method sets the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks
例子:
我们将创建一个简单的 PyQt5 应用程序,该应用程序在执行时会发出哔哔声,并将许多属性设置为 QApplication 对象,下面是实现
Python3
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100, 500, 400)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for components
def UiComponents(self):
# creating a push button
push = QPushButton("Press", self)
# setting geometry to the push button
push.setGeometry(100, 100, 120, 40)
# creating a label
label = QLabel("GeeksforGeeks", self)
# setting geometry to the label
label.setGeometry(100, 160, 200, 50)
# setting alignment to the label
label.setAlignment(Qt.AlignCenter)
# font
font = QFont("Arial", 12)
# setting font to the label
label.setFont(font)
# setting style sheet to the label
label.setStyleSheet("QLabel"
"{"
"border : 2px solid green;"
"background : lightgreen;"
"}")
# hiding the label
label.hide()
# adding action method to the push button
push.clicked.connect(lambda: do_something())
# method called by the push button when pressed
def do_something():
# unhide the label
label.show()
# create pyqt5 app
App = QApplication(sys.argv)
# setting cursor flashtime
App.setCursorFlashTime(100)
# setting application object name
App.setObjectName("GfG")
# setting application display name
App.setApplicationDisplayName("GfG PyQt5")
# beep sound will occur when application
# is opened
App.beep()
# message displayed about the Qt
App.aboutQt()
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出:
当我们首先执行代码时,会显示关于 Qt 的页面
然后我们的应用程序将开始