QCoreApplication

QCoreApplication class provides an event loop for Qt applications without UI. 更多

Inheritance diagram of PySide2.QtCore.QCoreApplication

继承者: QGuiApplication , QApplication

概要

虚函数

静态函数

详细描述

This class is used by non-GUI applications to provide their event loop. For non-GUI application that uses Qt, there should be exactly one QCoreApplication object. For GUI applications, see QGuiApplication . For applications that use the Qt Widgets module, see QApplication .

QCoreApplication contains the main event loop, where all events from the operating system (e.g., timer and network events) and other sources are processed and dispatched. It also handles the application’s initialization and finalization, as well as system-wide and application-wide settings.

事件循环和事件处理

开始事件循环通过调用 exec() . Long-running operations can call processEvents() to keep the application responsive.

In general, we recommend that you create a QCoreApplication , QGuiApplication QApplication 对象在您的 main() function as early as possible. exec() will not return until the event loop exits; e.g., when quit() 被调用。

Several static convenience functions are also provided. The QCoreApplication object is available from instance() . Events can be sent with sendEvent() or posted to an event queue with postEvent() . Pending events can be removed with removePostedEvents() or dispatched with sendPostedEvents() .

类提供 quit() slot and an aboutToQuit() 信号。

应用程序和库路径

应用程序有 applicationDirPath() applicationFilePath() . Library paths (see QLibrary ) 可以被检索采用 libraryPaths() and manipulated by setLibraryPaths() , addLibraryPath() ,和 removeLibraryPath() .

国际化和翻译

可以添加或移除翻译文件使用 installTranslator() and removeTranslator() . Application strings can be translated using translate() tr() and trUtf8() functions are implemented in terms of translate() .

访问命令行自变量

The command line arguments which are passed to QCoreApplication ‘s constructor should be accessed using the arguments() 函数。

注意

QCoreApplication removes option -qmljsdebugger="..." 。它剖析自变量为 qmljsdebugger ,然后删除此选项及其自变量。

对于更高级命令行选项处理,创建 QCommandLineParser .

区域设置

On Unix/Linux Qt is configured to use the system locale settings by default. This can cause a conflict when using POSIX functions, for instance, when converting between data types such as floats and strings, since the notation may differ between locales. To get around this problem, call the POSIX function setlocale(LC_NUMERIC,"C") right after initializing QApplication , QGuiApplication or QCoreApplication to reset the locale that is used for number formatting to “C”-locale.

class QCoreApplication

QCoreApplication(arg__1)

参数

arg__1 – 字符串列表

PySide2.QtCore.QCoreApplication. ApplicationFlags

New in version 4.8.

static PySide2.QtCore.QCoreApplication. addLibraryPath ( arg__1 )
参数

arg__1 – unicode

前置 path to the beginning of the library path list, ensuring that it is searched for libraries first. If path is empty or already in the path list, the path list is not changed.

The default path list consists of a single entry, the installation directory for plugins. The default installation directory for plugins is INSTALL/plugins ,其中 INSTALL is the directory where Qt was installed.

库路径被重置成默认当实例化的 QCoreApplication 被销毁。

static PySide2.QtCore.QCoreApplication. applicationDirPath ( )
返回类型

unicode

返回包含应用程序可执行文件的目录。

例如,若有安装 Qt 在 C:\Qt 目录,和运行 regexp example, this function will return “C:/Qt/examples/tools/regexp”.

On macOS and iOS this will point to the directory actually containing the executable, which may be inside an application bundle (if the application is bundled).

警告

On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.

static PySide2.QtCore.QCoreApplication. applicationFilePath ( )
返回类型

unicode

Returns the file path of the application executable.

例如,若有安装 Qt 在 /usr/local/qt 目录,和运行 regexp example, this function will return “/usr/local/qt/examples/tools/regexp/regexp”.

警告

On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.

static PySide2.QtCore.QCoreApplication. applicationName ( )
返回类型

unicode

PySide2.QtCore.QCoreApplication. applicationNameChanged ( )
static PySide2.QtCore.QCoreApplication. applicationPid ( )
返回类型

qint64

返回应用程序的当前进程 ID。

static PySide2.QtCore.QCoreApplication. applicationVersion ( )
返回类型

unicode

PySide2.QtCore.QCoreApplication. applicationVersionChanged ( )
static PySide2.QtCore.QCoreApplication. arguments ( )
返回类型

字符串列表

返回命令行自变量列表。

Usually .at(0) is the program name, .at(1) is the first argument, and .last() is the last argument. See the note below about Windows.

Calling this function is slow - you should store the result in a variable when parsing the command line.

警告

On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using fromLocal8Bit() ; hence it is not possible to pass, for example, Japanese command line arguments on a system that runs in a Latin1 locale. Most modern Unix systems do not have this limitation, as they are Unicode-based.

On Windows, the list is built from the argc and argv parameters only if modified argv/argc parameters are passed to the constructor. In that case, encoding problems might occur.

Otherwise, the are constructed from the return value of GetCommandLine() . As a result of this, the string given by .at(0) might not be the program name on Windows, depending on how the application was started.

static PySide2.QtCore.QCoreApplication. closingDown ( )
返回类型

bool

返回 true 若应用程序对象正在被销毁;否则返回 false .

另请参阅

startingUp()

static PySide2.QtCore.QCoreApplication. eventDispatcher ( )
返回类型

QAbstractEventDispatcher

Returns a pointer to the event dispatcher object for the main thread. If no event dispatcher exists for the thread, this function returns None .

static PySide2.QtCore.QCoreApplication. exec_ ( )
返回类型

int

进入主事件循环并等待,直到 exit() is called. Returns the value that was passed to exit() (which is 0 if exit() is called via quit() ).

有必要调用此函数以启动事件处理。主事件循环从窗口系统接收事件,并将其分派给应用程序 Widget。

要使应用程序履行空闲处理 (通过执行特殊函数,当没有待决事件时),使用 QTimer 采用 0 超时。更高级空闲处理方案可以达成使用 processEvents() .

推荐把清理代码连接到 aboutToQuit() signal, instead of putting it in your application’s main() function because on some platforms the call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function after the call.

static PySide2.QtCore.QCoreApplication. exit ( [ retcode=0 ] )
参数

retcode int

告诉应用程序采用返回代码去退出。

After this function has been called, the application leaves the main event loop and returns from the call to exec() exec() function returns returnCode . If the event loop is not running, this function does nothing.

按约定, returnCode 0 意味着成功,而任何非零值指示出错。

It’s good practice to always connect signals to this slot using a QueuedConnection . If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before “int main” calls exec() ), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

注意:不像同名 C 库函数,此函数 does return to the caller – it is event processing that stops.

另请参阅

quit() exec()

static PySide2.QtCore.QCoreApplication. flush ( )

注意

此函数被弃用。

此函数相当于调用 QCoreApplication::eventDispatcher()->flush() ,其也被弃用,见 flush() 。使用 sendPostedEvents() and processEvents() for more fine-grained control of the event loop instead.

在过去,此函数用于刷新特定平台本机事件队列。

static PySide2.QtCore.QCoreApplication. hasPendingEvents ( )
返回类型

bool

注意

此函数被弃用。

此函数返回 true 若有待决事件;否则返回 false 。待决事件可以来自窗口系统或张贴事件使用 postEvent() .

注意

此函数不是线程安全的。才可以在主线程中调用它仅当应用程序中没有其他线程在运行时 (包括 Qt 为自身目的而启动的线程)。

PySide2.QtCore.QCoreApplication. installNativeEventFilter ( filterObj )
参数

filterObj QAbstractNativeEventFilter

安装事件过滤器 filterObj 为所有本机接收事件,通过主线程中的应用程序。

事件过滤器 filterObj 接收事件凭借其 nativeEventFilter() function, which is called for all native events received in the main thread.

nativeEventFilter() function should return true if the event should be filtered, i.e. stopped. It should return false to allow normal Qt processing to continue: the native event can then be translated into a QEvent and handled by the standard Qt event filtering, e.g. installEventFilter() .

If multiple event filters are installed, the filter that was installed last is activated first.

注意

The filter function set here receives native messages, i.e. MSG or XCB event structs.

注意

Native event filters will be disabled in the application when the AA_PluginApplication attribute is set.

For maximum portability, you should always try to use QEvent and installEventFilter() whenever possible.

static PySide2.QtCore.QCoreApplication. installTranslator ( messageFile )
参数

messageFile QTranslator

返回类型

bool

添加翻译文件 translationFile 到用于翻译的翻译文件列表。

Multiple translation files can be installed. Translations are searched for in the reverse order in which they were installed, so the most recently installed translation file is searched first and the first translation file installed is searched last. The search stops as soon as a translation containing a matching string is found.

Installing or removing a QTranslator , or changing an installed QTranslator generates a LanguageChange event for the QCoreApplication instance. A QApplication instance will propagate the event to all toplevel widgets, where a reimplementation of changeEvent can re-translate the user interface by passing user-visible strings via the tr() function to the respective property setters. User-interface classes generated by Qt Designer provide a retranslateUi() function that can be called.

函数返回 true 当成功时和 false 当失败时。

另请参阅

removeTranslator() translate() load() Dynamic Translation

static PySide2.QtCore.QCoreApplication. instance ( )
返回类型

QCoreApplication

Returns a pointer to the application’s QCoreApplication (或 QGuiApplication / QApplication ) 实例。

若没有分配实例, None 被返回。

static PySide2.QtCore.QCoreApplication. isQuitLockEnabled ( )
返回类型

bool

static PySide2.QtCore.QCoreApplication. isSetuidAllowed ( )
返回类型

bool

返回 true 若允许应用程序在 UNIX 平台运行 setuid。

static PySide2.QtCore.QCoreApplication. libraryPaths ( )
返回类型

字符串列表

返回将搜索的应用程序路径列表当动态加载库时。

The return value of this function may change when a QCoreApplication is created. It is not recommended to call it before creating a QCoreApplication . The directory of the application executable ( not the working directory) is part of the list if it is known. In order to make it known a QCoreApplication has to be constructed as it will use argv[0] to find it.

Qt provides default library paths, but they can also be set using a qt.conf file. Paths specified in this file will override default values. Note that if the qt.conf file is in the directory of the application executable, it may not be found until a QCoreApplication is created. If it is not found when calling this function, the default library paths will be used.

The list will include the installation directory for plugins if it exists (the default installation directory for plugins is INSTALL/plugins ,其中 INSTALL is the directory where Qt was installed). The colon separated entries of the QT_PLUGIN_PATH environment variable are always added. The plugin installation directory (and its existence) may change when the directory of the application executable becomes known.

若希望遍历列表,可以使用 foreach 伪关键字:

for path in app.libraryPaths():
    do_something(path)
												

另请参阅

setLibraryPaths() addLibraryPath() removeLibraryPath() QLibrary How to 创建 Qt 插件

PySide2.QtCore.QCoreApplication. notify ( arg__1 , arg__2 )
参数
返回类型

bool

发送 event to receiver : receiver ->event( event ). Returns the value that is returned from the receiver’s event handler. Note that this function is called for all events sent to any object in any thread.

For certain types of events (e.g. mouse and key events), the event will be propagated to the receiver’s parent and so on up to the top-level object if the receiver is not interested in the event (i.e., it returns false ).

有 5 种不同办法可以处理事件。重新实现此虚函数只是它们之一。以下列出了所有 5 种途径:

  1. 重实现 paintEvent() , mousePressEvent() and so on. This is the most common, easiest, and least powerful way.

  2. Reimplementing this function. This is very powerful, providing complete control; but only one subclass can be active at a time.

  3. Installing an event filter on instance() . Such an event filter is able to process all events for all widgets, so it’s just as powerful as reimplementing ; furthermore, it’s possible to have more than one application-global event filter. Global event filters even see mouse events for disabled widgets . Note that application event filters are only called for objects that live in the main thread.

  4. 重实现 event() (as QWidget does). If you do this you get Tab key presses, and you get to see the events before any widget-specific event filters.

  5. Installing an event filter on the object. Such an event filter gets all the events, including Tab and Shift+Tab key press events, as long as they do not change the focus widget.

未来方向: This function will not be called for objects that live outside the main thread in Qt 6. Applications that need that functionality should find other solutions for their event inspection needs in the meantime. The change may be extended to the main thread, causing this function to be deprecated.

警告

If you override this function, you must ensure all threads that process events stop doing so before your application object begins destruction. This includes threads started by other libraries that you may be using, but does not apply to Qt’s own threads.

static PySide2.QtCore.QCoreApplication. organizationDomain ( )
返回类型

unicode

PySide2.QtCore.QCoreApplication. organizationDomainChanged ( )
static PySide2.QtCore.QCoreApplication. organizationName ( )
返回类型

unicode

PySide2.QtCore.QCoreApplication. organizationNameChanged ( )
static PySide2.QtCore.QCoreApplication. postEvent ( receiver , event [ , priority=Qt.NormalEventPriority ] )
参数

添加事件 event ,采用对象 receiver 作为事件接收者,到事件队列并立即返回。

事件必须在堆上被分配,因为 Post 事件队列将获取事件的所有权,且事件一旦已被张贴就会被删除。它是 not safe 去访问事件,其它已被张贴之后。

When control returns to the main event loop, all events that are stored in the queue will be sent using the notify() 函数。

Events are sorted in descending priority order, i.e. events with a high priority are queued before events with a lower priority priority can be any integer value, i.e. between INT_MAX and INT_MIN, inclusive; see EventPriority for more details. Events with equal priority will be processed in the order posted.

static PySide2.QtCore.QCoreApplication. processEvents ( [ flags=QEventLoop.AllEvents ] )
参数

flags ProcessEventsFlags

处理所有调用线程待决事件,根据指定 flags 直到没有更多要处理事件为止。

可以偶尔调用此函数当程序忙于履行长时间操作时 (如:拷贝文件)。

在正在运行连续调用此函数的本地循环事件中,若没有事件循环, DeferredDelete 事件不会被处理。这会影响 Widget 的行为,如 QToolTip 依赖 DeferredDelete 事件才能正确运行。替代是调用 sendPostedEvents() 从本地循环中。

调用此函数仅处理调用线程的事件,并在处理所有可用事件后返回。可用事件是在函数调用之前的队列事件。这意味着当函数运行时张贴的事件将被队列,直到稍后一轮的事件处理为止。

static PySide2.QtCore.QCoreApplication. processEvents ( flags , maxtime )
参数
  • flags ProcessEventsFlags

  • maxtime int

此函数重载 processEvents() .

处理调用线程待决事件以 ms 毫秒为单位或直到没有更多要处理事件为止,以较短者为准。

可以偶尔调用此函数当程序忙于做长时间操作时 (如:拷贝文件)。

调用此函数仅处理调用线程的事件。

注意

不像 processEvents() 重载,此函数还处理函数运行时发布的事件。

另请参阅

exec() QTimer processEvents()

static PySide2.QtCore.QCoreApplication. quit ( )

告诉应用程序要退出采用返回代码 0 (当成功时)。相当于调用 exit (0).

It’s common to connect the lastWindowClosed() signal to , and you also often connect e.g. clicked() or signals in QAction , QMenu ,或 QMenuBar 到它。

It’s good practice to always connect signals to this slot using a QueuedConnection . If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before “int main” calls exec() ), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

范例:

quitButton = QPushButton("Quit")
quitButton.clicked.connect(app.quit)
												

另请参阅

exit() aboutToQuit() lastWindowClosed()

static PySide2.QtCore.QCoreApplication. removeLibraryPath ( arg__1 )
参数

arg__1 – unicode

移除 path 从库路径列表。若 path 为空或不在路径列表中,列表无变化。

库路径被重置成默认当实例化的 QCoreApplication 被销毁。

PySide2.QtCore.QCoreApplication. removeNativeEventFilter ( filterObj )
参数

filterObj QAbstractNativeEventFilter

移除事件 filterObject from this object. The request is ignored if such an event filter has not been installed.

All event filters for this object are automatically removed when this object is destroyed.

It is always safe to remove an event filter, even during event filter activation (i.e. from the nativeEventFilter() function).

static PySide2.QtCore.QCoreApplication. removePostedEvents ( receiver [ , eventType=0 ] )
参数

Removes all events of the given eventType that were posted using postEvent() for receiver .

The events are not dispatched, instead they are removed from the queue. You should never need to call this function. If you do call it, be aware that killing events may cause receiver to break one or more invariants.

receiver is None ,事件的 eventType are removed for all objects. If eventType is 0, all the events are removed for receiver . You should never call this function with eventType of 0.

static PySide2.QtCore.QCoreApplication. removeTranslator ( messageFile )
参数

messageFile QTranslator

返回类型

bool

移除翻译文件 translationFile from the list of translation files used by this application. (It does not delete the translation file from the file system.)

函数返回 true 当成功时和 false 当失败时。

static PySide2.QtCore.QCoreApplication. sendEvent ( receiver , event )
参数
返回类型

bool

发送事件 event 直接到接收者 receiver ,使用 notify() function. Returns the value that was returned from the event handler.

事件 not 被删除,当事件被发送后。正常途径是在堆栈上创建事件,例如:

event = QMouseEvent(QEvent.MouseButtonPress, pos, 0, 0, 0)
QApplication.sendEvent(mainWindow, event)
												
static PySide2.QtCore.QCoreApplication. sendPostedEvents ( [ receiver=None [ , event_type=0 ] ] )
参数

立即分派之前队列的所有事件采用 postEvent() and which are for the object receiver 和事件类型 event_type .

来自窗口系统的事件 not 通过此函数分派,而是通过 processEvents() .

receiver is None ,事件的 event_type 为所有对象发送。若 event_type 为 0,所有事件被发送给 receiver .

注意

此方法必须被调用从线程以其 QObject 参数, receiver ,存活。

static PySide2.QtCore.QCoreApplication. setApplicationName ( application )
参数

application – unicode

另请参阅

applicationName()

static PySide2.QtCore.QCoreApplication. setApplicationVersion ( version )
参数

version – unicode

static PySide2.QtCore.QCoreApplication. setAttribute ( attribute [ , on=true ] )
参数
  • attribute ApplicationAttribute

  • on bool

设置属性 attribute if on 为 true;否则清零属性。

注意

某些应用程序属性必须被设置 before 创建 QCoreApplication 实例。参考 ApplicationAttribute 文档编制,了解更多信息。

另请参阅

testAttribute()

static PySide2.QtCore.QCoreApplication. setEventDispatcher ( eventDispatcher )
参数

eventDispatcher QAbstractEventDispatcher

将主线程事件分派程序设为 eventDispatcher 。这才有可能,只要尚未安装事件分派程序。也就是,先于 QCoreApplication 已被实例化。此方法获取对象的所有权。

另请参阅

eventDispatcher()

static PySide2.QtCore.QCoreApplication. setLibraryPaths ( arg__1 )
参数

arg__1 – 字符串列表

把要搜索的目录列表 (当加载库时) 设为 paths 。所有现有路径被删除且路径列表将由给定路径组成按 paths .

库路径被重置成默认当实例化的 QCoreApplication 被销毁。

static PySide2.QtCore.QCoreApplication. setOrganizationDomain ( orgDomain )
参数

orgDomain – unicode

static PySide2.QtCore.QCoreApplication. setOrganizationName ( orgName )
参数

orgName – unicode

static PySide2.QtCore.QCoreApplication. setQuitLockEnabled ( enabled )
参数

enabled bool

static PySide2.QtCore.QCoreApplication. setSetuidAllowed ( allow )
参数

allow bool

允许应用程序在 UNIX 平台运行 setuid 若 allow 为 true。

allow is false (the default) and Qt detects the application is running with an effective user id different than the real user id, the application will be aborted when a QCoreApplication instance is created.

Qt is not an appropriate solution for setuid programs due to its large attack surface. However some applications may be required to run in this manner for historical reasons. This flag will prevent Qt from aborting the application when this is detected, and must be set before a QCoreApplication instance is created.

注意

强烈推荐不启用此选项,由于它引入安全风险。

另请参阅

isSetuidAllowed()

PySide2.QtCore.QCoreApplication. shutdown ( )
static PySide2.QtCore.QCoreApplication. startingUp ( )
返回类型

bool

返回 true 若应用程序对象尚未被创建;否则返回 false .

另请参阅

closingDown()

static PySide2.QtCore.QCoreApplication. testAttribute ( attribute )
参数

attribute ApplicationAttribute

返回类型

bool

返回 true 若属性 attribute 已设置;否则返回 false .

另请参阅

setAttribute()

static PySide2.QtCore.QCoreApplication. translate ( context , key [ , disambiguation=None [ , n=-1 ] ] )
参数
  • context – str

  • key – str

  • disambiguation – str

  • n int

返回类型

unicode

Returns the translation text for sourceText , by querying the installed translation files. The translation files are searched from the most recently installed file back to the first installed file.

tr() provides this functionality more conveniently.

context is typically a class name (e.g., “MyDialog”) and sourceText is either English text or a short identifying text.

disambiguation is an identifying string, for when the same sourceText is used in different roles within the same context. By default, it is None .

QTranslator and tr() documentation for more information about contexts, disambiguations and comments.

n is used in conjunction with %n to support plural forms. See tr() 了解细节。

If none of the translation files contain a translation for sourceText in context , this function returns a QString equivalent of sourceText .

This function is not virtual. You can use alternative translation techniques by subclassing QTranslator .

class QCoreApplication ( args )

Constructs a Qt kernel application. Kernel applications are applications without a graphical user interface. These type of applications are used at the console or as server processes.

args argument is processed by the application, and made available in a more convenient form by the arguments() 方法。