Qapplication python что делает
The QApplication class manages the GUI application’s control flow and main settings. It specializes in the QGuiApplication with some functionality needed for QWidget based applications. It handles widget specific initialization, finalization. For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2, or more windows at any given time. For non-QWidget based Qt applications, use QGuiApplication instead, as it does not depend on the QtWidgets library.
We then create a window instance and execute the QApplication object in the event loop using sys.exit(App.exec()) command, below are some useful and frequently methods and property used with the QApplication object.
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
Example:
We will create a simple PyQt5 application which produces a beep sound when it gets executed and many properties are set to the QApplication object, below is the implementation
QApplication#
QApplication specializes QGuiApplication with some functionality needed for QWidget -based applications. It handles widget specific initialization, finalization.
For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time. For non- QWidget based Qt applications, use QGuiApplication instead, as it does not depend on the QtWidgets library.
Some GUI applications provide a special batch mode ie. provide command line arguments for executing tasks without manual intervention. In such non-GUI mode, it is often sufficient to instantiate a plain QCoreApplication to avoid unnecessarily initializing resources needed for a graphical user interface. The following example shows how to dynamically create an appropriate type of application instance:
The QApplication object is accessible through the instance() function that returns a pointer equivalent to the global qApp pointer.
QApplication ‘s main areas of responsibility are:
-
It initializes the application with the user’s desktop settings such as palette() , font() and doubleClickInterval() . It keeps track of these properties in case the user changes the desktop globally, for example through some kind of control panel.
-
It performs event handling, meaning that it receives events from the underlying window system and dispatches them to the relevant widgets. By using sendEvent() and postEvent() you can send your own events to widgets.
-
It parses common command line arguments and sets its internal state accordingly. See the constructor documentation below for more details.
-
It defines the application’s look and feel, which is encapsulated in a QStyle object. This can be changed at runtime with setStyle() .
-
It provides localization of strings that are visible to the user via translate() .
-
It provides some magical objects like the clipboard() .
-
It knows about the application’s windows. You can ask which widget is at a certain position using widgetAt() , get a list of topLevelWidgets() and closeAllWindows() , etc.
-
It manages the application’s mouse cursor handling, see setOverrideCursor()
Since the QApplication object does so much initialization, it must be created before any other objects related to the user interface are created. QApplication also deals with common command line arguments. Hence, it is usually a good idea to create it before any interpretation or modification of argv is done in the application itself.
|
Groups of functions |
|
|---|---|
|
System settings |
desktopSettingsAware() , setDesktopSettingsAware() , cursorFlashTime() , setCursorFlashTime() , doubleClickInterval() , setDoubleClickInterval() , setKeyboardInputInterval() , wheelScrollLines() , setWheelScrollLines() , palette() , setPalette() , font() , setFont() , fontMetrics(). |
|
Event handling |
exec() , processEvents() , exit() , quit() . sendEvent() , postEvent() , sendPostedEvents() , removePostedEvents() , notify() . |
|
GUI Styles |
style() , setStyle() . |
|
Text handling |
installTranslator() , removeTranslator() translate() . |
|
Widgets |
allWidgets() , topLevelWidgets() , activePopupWidget() , activeModalWidget() , clipboard() , focusWidget() , activeWindow() , widgetAt() . |
|
Advanced cursor handling |
overrideCursor() , setOverrideCursor() , restoreOverrideCursor() . |
|
Miscellaneous |
closeAllWindows() , startingUp() , closingDown() . |
See also
QCoreApplication QAbstractEventDispatcher QEventLoop QSettings
arg__1 – list of strings
static PySide6.QtWidgets.QApplication. aboutQt ( ) #
Displays a simple message box about Qt. The message includes the version number of Qt being used by the application.
This is useful for inclusion in the Help menu of an application, as shown in the Menus example.
This function is a convenience slot for aboutQt() .
static PySide6.QtWidgets.QApplication. activeModalWidget ( ) # Return type
Returns the active modal widget.
A modal widget is a special top-level widget which is a subclass of QDialog that specifies the modal parameter of the constructor as true. A modal widget must be closed before the user can continue with other parts of the program.
Modal widgets are organized in a stack. This function returns the active modal widget at the top of the stack.
Returns the active popup widget.
A popup widget is a special top-level widget that sets the Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application opens a popup widget, all events are sent to the popup. Normal widgets and modal widgets cannot be accessed before the popup widget is closed.
Only other popup widgets may be opened when a popup widget is shown. The popup widgets are organized in a stack. This function returns the active popup widget at the top of the stack.
Returns the application top-level window that has the keyboard input focus, or None if no application window has the focus. There might be an activeWindow() even if there is no focusWidget() , for example if no widget in that window accepts key events.
duration – int
Causes an alert to be shown for widget if the window is not the active window. The alert is shown for msec milliseconds. If msec is zero (the default), then the alert is shown indefinitely until the window becomes active again.
Currently this function does nothing on Qt for Embedded Linux.
On macOS, this works more at the application level and will cause the application icon to bounce in the dock.
On Windows, this causes the window’s taskbar entry to flash for a time. If msec is zero, the flashing will stop and the taskbar entry will turn a different color (currently orange).
On X11, this will cause the window to be marked as “demands attention”, the window must not be hidden (i.e. not have hide() called on it, but be visible in some sort of way) in order for this to work.
static PySide6.QtWidgets.QApplication. allWidgets ( ) # Return type
Returns a list of all the widgets in the application.
The list is empty ( isEmpty() ) if there are no widgets.
Some of the widgets may be hidden.
This property holds toggles automatic SIP (software input panel) visibility.
Set this property to true to automatically display the SIP when entering widgets that accept keyboard input. This property only affects widgets with the WA_InputMethodEnabled attribute set, and is typically used to launch a virtual keyboard on devices which have very few or no keys.
The property only has an effect on platforms that use software input panels.
The default is platform dependent.
static PySide6.QtWidgets.QApplication. beep ( ) #
Sounds the bell, using the default volume and sound. The function is not available in Qt for Embedded Linux.
static PySide6.QtWidgets.QApplication. closeAllWindows ( ) #
Closes all top-level windows.
This function is particularly useful for applications with many top-level windows.
The windows are closed in random order, until one window does not accept the close event. The application quits when the last window was successfully closed, unless quitOnLastWindowClosed is set to false. To trigger application termination from e.g. a menu, use quit() instead of this function.
See also
quitOnLastWindowClosed lastWindowClosed() close() closeEvent() lastWindowClosed() quit() topLevelWidgets() isWindow()
This property holds the text cursor’s flash (blink) time in milliseconds.
The flash time is the time required to display, invert and restore the caret display. Usually the text cursor is displayed for half the cursor flash time, then hidden for the same amount of time, but this may vary.
The default value on X11 is 1000 milliseconds. On Windows, the Control Panel value is used and setting this property sets the cursor flash time for all applications.
We recommend that widgets do not cache this value as it may change at any time if the user changes the global desktop settings.
This property may hold a negative value, for instance if cursor blinking is disabled.
This property holds the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used.
PySide6.QtWidgets.QApplication. exec_ ( ) # Return type
This signal is emitted when the widget that has keyboard focus changed from old to now , i.e., because the user pressed the tab-key, clicked into a widget or changed the active window. Both old and now can be None .
The signal is emitted after both widget have been notified about the change through QFocusEvent .
Returns the application widget that has the keyboard input focus, or None if no widget in this application has the focus.
This is an overloaded function.
Returns the default font for the widget . If a default font was not registered for the widget ‘s class, it returns the default font of its nearest registered superclass.
className – str
This is an overloaded function.
Returns the font for widgets of the given className .
This function is deprecated.
Use the QFontMetricsF constructor instead. Returns display (screen) font metrics for the application font.
arg__1 – UIEffect
Returns true if effect is enabled; otherwise returns false .
By default, Qt will try to use the desktop settings. To prevent this, call setDesktopSettingsAware(false).
All effects are disabled on screens running at less than 16-bit color depth.
This property holds the time limit in milliseconds that distinguishes a key press from two consecutive key presses.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used.
static PySide6.QtWidgets.QApplication. palette ( arg__1 ) # Parameters
If a widget is passed, the default palette for the widget’s class is returned. This may or may not be the application palette. In most cases there is no special palette for certain types of widgets, but one notable exception is the popup menu under Windows, if the user has defined a special background color for menus in the display settings.
className – str
This is an overloaded function.
Returns the palette for widgets of the given className .
Sets the active window to the active widget in response to a system event. The function is called from the platform specific event handlers.
This function does not set the keyboard focus to the active widget. Call activateWindow() instead.
It sets the activeWindow() and focusWidget() attributes and sends proper WindowActivate / WindowDeactivate and FocusIn / FocusOut events to all appropriate widgets. The window will then be painted in active state (e.g. cursors in line edits will blink), and it will have tool tips enabled.
enabled – bool
This property holds toggles automatic SIP (software input panel) visibility.
Set this property to true to automatically display the SIP when entering widgets that accept keyboard input. This property only affects widgets with the WA_InputMethodEnabled attribute set, and is typically used to launch a virtual keyboard on devices which have very few or no keys.
The property only has an effect on platforms that use software input panels.
The default is platform dependent.
static PySide6.QtWidgets.QApplication. setCursorFlashTime ( arg__1 ) # Parameters
arg__1 – int
This property holds the text cursor’s flash (blink) time in milliseconds.
The flash time is the time required to display, invert and restore the caret display. Usually the text cursor is displayed for half the cursor flash time, then hidden for the same amount of time, but this may vary.
The default value on X11 is 1000 milliseconds. On Windows, the Control Panel value is used and setting this property sets the cursor flash time for all applications.
We recommend that widgets do not cache this value as it may change at any time if the user changes the global desktop settings.
This property may hold a negative value, for instance if cursor blinking is disabled.
arg__1 – int
This property holds the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used.
arg__1 – UIEffect
enable – bool
Enables the UI effect effect if enable is true, otherwise the effect will not be used.
All effects are disabled on screens running at less than 16-bit color depth.
className – str
Changes the default application font to font . If className is passed, the change applies only to classes that inherit className (as reported by inherits() ).
On application start-up, the default font depends on the window system. It can vary depending on both the window system version and the locale. This function lets you override the default font; but overriding may be a bad idea because, for example, some locales need extra large fonts to support their special characters.
Do not use this function in conjunction with Qt Style Sheets . The font of an application can be customized using the “font” style sheet property. To set a bold font for all QPushButtons, set the application styleSheet() as ” QPushButton < font: bold >”
arg__1 – int
This property holds the time limit in milliseconds that distinguishes a key press from two consecutive key presses.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used.
className – str
Changes the application palette to palette .
If className is passed, the change applies only to widgets that inherit className (as reported by inherits() ). If className is left 0, the change affects all widgets, thus overriding any previously set class specific palettes.
The palette may be changed according to the current GUI style in polish() .
Do not use this function in conjunction with Qt Style Sheets . When using style sheets, the palette of a widget can be customized using the “color”, “background-color”, “selection-color”, “selection-background-color” and “alternate-background-color”.
Some styles do not use the palette for all drawing, for instance, if they make use of native theme engines. This is the case for the Windows Vista and macOS styles.
l – int
This property holds the minimum distance required for a drag and drop operation to start..
If you support drag and drop in your application, and want to start a drag and drop operation after the user has moved the cursor a certain distance with a button held down, you should use this property’s value as the minimum distance required.
For example, if the mouse position of the click is stored in startPos and the current position (e.g. in the mouse move event) is currentPos , you can find out if a drag should be started with code like this:
Qt uses this value internally, e.g. in QFileDialog .
The default value (if the platform doesn’t provide a different default) is 10 pixels.
ms – int
This property holds the time in milliseconds that a mouse button must be held down before a drag and drop operation will begin.
If you support drag and drop in your application, and want to start a drag and drop operation after the user has held down a mouse button for a certain amount of time, you should use this property’s value as the delay.
Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit , for starting a drag.
The default value is 500 ms.
Sets the application’s GUI style to style . Ownership of the style object is transferred to QApplication , so QApplication will delete the style object on application exit or when a new style is set and the old style is still the parent of the application object.
When switching application styles, the color palette is set back to the initial colors or the system defaults. This is necessary since certain styles have to adapt the color palette to be fully style-guide compliant.
Setting the style before a palette has been set, i.e., before creating QApplication , will cause the application to use standardPalette() for the palette.
Qt style sheets are currently not supported for custom QStyle subclasses. We plan to address this in some future release.
arg__1 – str
This is an overloaded function.
Requests a QStyle object for style from the QStyleFactory .
The string must be one of the keys() , typically one of “windows”, “windowsvista”, “fusion”, or “macos”. Style names are case insensitive.
Returns None if an unknown style is passed, otherwise the QStyle object returned is set as the application’s GUI style.
To ensure that the application’s style is set correctly, it is best to call this function before the QApplication constructor, if possible.
sheet – str
This property holds the application style sheet.
By default, this property returns an empty string unless the user specifies the -stylesheet option on the command line when running the application.
arg__1 – int
This property holds the number of lines to scroll a widget, when the mouse wheel is rotated..
If the value exceeds the widget’s number of visible lines, the widget should interpret the scroll operation as a single page up or page down. If the widget is an item view class , then the result of scrolling one line depends on the setting of the widget’s scroll mode . Scroll one line can mean scroll one item or scroll one pixel .
By default, this property has a value of 3.
See also
wheelScrollLines()
This property holds the minimum distance required for a drag and drop operation to start..
If you support drag and drop in your application, and want to start a drag and drop operation after the user has moved the cursor a certain distance with a button held down, you should use this property’s value as the minimum distance required.
For example, if the mouse position of the click is stored in startPos and the current position (e.g. in the mouse move event) is currentPos , you can find out if a drag should be started with code like this:
Qt uses this value internally, e.g. in QFileDialog .
The default value (if the platform doesn’t provide a different default) is 10 pixels.
This property holds the time in milliseconds that a mouse button must be held down before a drag and drop operation will begin.
If you support drag and drop in your application, and want to start a drag and drop operation after the user has held down a mouse button for a certain amount of time, you should use this property’s value as the delay.
PyQt6 — полное руководство для новичков

К старту курса по разработке на Python делимся детальным руководством по работе с современным PyQt. Чтобы читать было удобнее, мы объединили несколько статей в одну:
За подробностями приглашаем под кат.
Простое приложение Hello World! на Python и Qt6
PyQt — это библиотека Python для создания приложений с графическим интерфейсом с помощью инструментария Qt. Созданная в Riverbank Computing, PyQt является свободным ПО (по лицензии GPL) и разрабатывается с 1999 года. Последняя версия PyQt6 — на основе Qt 6 — выпущена в 2021 году, и библиотека продолжает обновляться. Это руководство можно также использовать для PySide2, PySide6 и PyQt5.
Сегодня используются две основные версии: PyQt5 на основе Qt5 и PyQt6 на основе Qt6. Обе почти полностью совместимы, за исключением импорта и отсутствия поддержки некоторых продвинутых модулей из Qt6. В PyQt6 вносятся изменения в работу пространств имён и флагов, но ими легко управлять. В этом руководстве мы узнаем, как использовать PyQt6 для создания настольных приложений.
Сначала создадим несколько простых окон на рабочем столе, чтобы убедиться, что PyQt работает, и разберём базовые понятия. Затем кратко изучим цикл событий и то, как он связан с программированием графического интерфейса на Python. В заключение поговорим о QMainWindow с полезными элементами интерфейса, такими как панели инструментов и меню. Подробно я расскажу о них в следующих руководствах.
Создание приложения
Сначала создадим новый файл Python с любым названием (например app.py) и сохраним его. Исходный код приложения показан ниже. Введите его полностью и постарайтесь не ошибиться. Если что-то напутаете, Python укажет, что именно:
Запускаем приложение из командной строки, как и любой скрипт Python:
Выполнив его, мы увидим окно. В Qt автоматически создаётся окно с обычным оформлением, возможностью его перетаскивать и менять размер. То, что вы увидите, зависит от платформы, где этот пример выполняется. Вот как отображается это окно на Windows, macOS и Linux (Ubuntu):

Окно на Windows, macOS и Linux
Разбор кода
Пройдём код построчно, чтобы понять, что именно происходит. Сначала мы импортируем классы PyQt для приложения: здесь это обработчик приложения QApplication и базовый пустой виджет графического интерфейса QWidget (оба из модуля QtWidgets):
Основные модули для Qt: QtWidgets, QtGui и QtCore.
Возможен ещё from import * , но этот вид импорта обычно не приветствуется в Python. Дальше создаём экземпляр QApplication и передаём sys.arg (список Python с аргументами командной строки, передаваемыми приложению):
Если не будете использовать аргументы командной строки для управления Qt, передайте пустой список:
Затем создаём экземпляр QWidget, используя имя переменной window:
В Qt все виджеты верхнего уровня — окна, то есть у них нет родительского элемента и они не вложены в другой виджет или макет. В принципе, окно можно создать, используя любой виджет.
Виджеты без родительского элемента по умолчанию невидимы. Поэтому после создания объекта window необходимо всегда вызывать функцию .show(), чтобы сделать его видимым. .show() можно удалить, но тогда, запустив приложение, вы не сможете выйти из него!
В окне находится пользовательский интерфейс приложения. У каждого приложения он как минимум один. Приложение (по умолчанию) завершает работу при закрытии последнего окна.
Наконец, вызываем app.exec(), чтобы запустить цикл события.
Что такое «цикл событий»?
Прежде чем вывести окно на экран, разберём ключевые понятия, касающиеся организации приложений в мире Qt. Если вам уже знакомы циклы событий, можете пропустить эту часть статьи.
Основной элемент всех приложений в Qt — класс QApplication. Для работы каждому приложению нужен один — и только один — объект QApplication, который содержит цикл событий приложения. Это основной цикл, управляющий всем взаимодействием пользователя с графическим интерфейсом:

При каждом взаимодействии с приложением — будь то нажатие клавиши, щелчок или движение мыши — генерируется событие, которое помещается в очередь событий. В цикле событий очередь проверяется на каждой итерации: если найдено ожидающее событие, оно вместе с управлением передаётся определённому обработчику этого события. Последний обрабатывает его, затем возвращает управление в цикл событий и ждёт новых событий. Для каждого приложения выполняется только один цикл событий.
Класс QApplication содержит цикл событий Qt (нужен один экземпляр QApplication). Приложение ждёт в цикле событий новое событие, которое будет сгенерировано при выполнении действия. Всегда выполняется только один цикл событий.
QMainWindow
Итак, в Qt любые виджеты могут быть окнами. Например, если заменить QtWidget на QPushButton. В этом примере получается окно с одной нажимаемой кнопкой:
Классно, но не очень полезно на самом деле: редко когда нужен пользовательский интерфейс, состоящий только из одного элемента управления. Зато возможность с помощью макетов вкладывать одни виджеты в другие позволяет создавать сложные пользовательские интерфейсы внутри пустого QWidget.
В Qt уже есть решение для окна — виджет QMainWindow, имеющий стандартные функции окна для использования в приложениях, который содержит панели инструментов, меню, строку состояния, закрепляемые виджеты и многое другое. Рассмотрим эти расширенные функции позже, а пока добавим в приложение простой, пустой QMainWindow:
Запускаем и видим главное окно. Точно такое же, как и раньше.
QMainWindow пока не очень интересный. Добавим контент. Чтобы сделать настраиваемое окно, лучше создать подкласс QMainWindow, а затем настроить окно в блоке __init__. Так окно станет независимым в плане поведения. Итак, добавляем подкласс QMainWindow — MainWindow:
Для этого демо используем QPushButton. Основные виджеты Qt всегда импортируются из пространства имён QtWidgets, как и классы QMainWindow и QApplication. При использовании QMainWindow задействуем .setCentralWidget для размещения виджета (здесь виджет — QPushButton) в QMainWindow, по умолчанию он занимает всё окно. Как добавлять в окна несколько виджетов? Об этом поговорим рассмотрим в руководстве по макетам.
При создании подкласса из класса Qt, чтобы разрешить Qt настраивать объект, всегда нужно вызывать функцию super __init__.
В блоке __init__ сначала используем .setWindowTitle(), чтобы поменять заголовок главного окна. Затем добавляем первый виджет — QPushButton — в середину окна. Это один из основных виджетов Qt. При создании кнопки можно ввести текст, который будет на ней отображаться. Вызываем .setCentralWidget() в окне. Это специальная функция QMainWindow, которая позволяет установить виджет на середину окна.
Запускаем и снова видим окно, но на этот раз с виджетом QPushButton в центре. Нажатие кнопки ничего не даст — с этим мы разберёмся после:

QMainWindow с одной кнопкой QPushButton на Windows, macOS и Linux
Скоро мы подробно рассмотрим другие виджеты, но, если вам не терпится и хочется забежать вперёд, можете заглянуть в документацию QWidget. Попробуйте добавить различные виджеты в окно.
Изменение размеров окон и виджетов
Сейчас размер окна можно свободно поменять: щёлкните мышью на любой угол и перетаскивайте, меняя таким образом размер. Можно дать возможность пользователям самим менять размер приложений, а можно установить ограничения на минимальные или максимальные размеры или фиксированный размер окна.
В Qt размеры определяются с помощью объекта QSize. Он принимает параметры ширины и высоты. Например, так создаётся окно фиксированного размера 400 x 300 пикселей:
Запускаем и видим окно фиксированного размера. Поменять его размер не получится.

Окно фиксированного размера
Элемент управления maximize отключён на Windows и Linux. На macOS можно развернуть приложение на весь экран, но размер центрального виджета не изменится.
Кроме .setFixedSize() можно также вызвать .setMinimumSize() и .setMaximumSize(), чтобы установить минимальный и максимальный размеры соответственно. Попробуйте сами! Эти методы регулирования размеров работают в любом виджете. Продолжить изучение Python вы сможете на наших курсах:
А ещё вы можете приобрести книгу автора этих уроков или продолжить чтение.
Слоты и сигналы
Ранее мы рассмотрели классы QApplication и QMainWindow, цикл событий и добавили в окно простой виджет. А теперь изучим механизмы Qt для взаимодействия виджетов и окон друг с другом. В статью внесены изменения, связанные с PyQt6.
Мы создали окно и добавили в него простой виджет push button, но кнопка пока бесполезна. Нужно связать действие нажатия кнопки с происходящим. В Qt это делается с помощью сигналов и слотов или событий.
Сигналы — это уведомления, отправляемые виджетами, когда что-то происходит. Этим «чем-то» может быть что угодно — нажатие кнопки, изменение текста в поле ввода или изменение текста в окне. Многие сигналы инициируются в ответ на действия пользователя, но не только: в сигналах могут отправляться данные с дополнительным контекстом произошедшего.
Можно также писать собственные сигналы, их мы рассмотрим позже.
Слоты в Qt — это приёмники сигналов. Слотом в приложении на Python можно сделать любую функцию (или метод), просто подключив к нему сигнал. Принимающая функция получает данные, отправляемые ей в сигнале. У многих виджетов Qt есть встроенные слоты, а значит, виджеты можно подключать друг к другу напрямую.
Рассмотрим основные сигналы Qt и их использование для подключения виджетов в приложениях. Сохраните эту заготовку приложения в файле app.py:
Сигналы QPushButton
Сейчас у нас есть QMainWindow с центральным виджетом QPushButton. Подключим эту кнопку к пользовательскому методу Python. Создадим простой настраиваемый слот the_button_was_clicked, принимающий сигнал clicked от QPushButton:
Запускаем. Если нажать на кнопку, в консоли появится текст Clicked! («Нажата!»):
Получение данных
В сигналах может отправляться дополнительная информация о произошедшем. И сигнал .clicked — не исключение: с его помощью сообщается о нажатом (или переключенном) состоянии кнопки. Для обычных кнопок это значение всегда False, поэтому первый слот проигнорировал эти данные. Включим возможность нажатия кнопки, чтобы увидеть этот эффект. Ниже добавляется второй слот и выводится состояние нажатия:
Запускаем! Если нажать на кнопку, она подсветится и станет checked («Нажатой»). Чтобы отключить её, нажимаем ещё раз. Найдите состояние нажатия в консоли:
К сигналу подключается сколько угодно слотов, в которых можно реагировать сразу на несколько версий сигналов.
Хранение данных
Текущее состояние виджета на Python часто хранят в переменной, что позволяет работать со значениями без доступа к исходному виджету. Причём для их хранения используются отдельные переменные или словарь. В следующем примере сохраняем значение кнопки checked («Нажата») в переменной button_is_checked в self:
Сначала устанавливаем переменной значение по умолчанию True, а затем используем это значение, чтобы установить исходное состояние виджета. Когда состояние виджета меняется, получаем сигнал и соответственно обновляем переменную.
Эта же схема применима к любым виджетам PyQt. Если в виджете нет сигнала, которым отправляется текущее состояние, нужно получить значение из виджета прямо в обработчике. Например, здесь мы проверяем состояние checked («Нажата») в нажатом обработчике:
Сохраним ссылку на кнопку в self, чтобы получить к ней доступ в слоте.
Сигнал released срабатывает, когда кнопка отпускается, при этом состояние нажатия не отправляется. Его получают из кнопки в обработчике, используя .isChecked().
Изменение интерфейса
Мы уже видели, как принимаются сигналы и выводятся на консоль результаты. Но что происходит с интерфейсом, когда нажимают на кнопку? Обновим метод слота, чтобы изменить кнопку, поменяв текст, отключив её и сделав её недоступной. И отключим пока состояние, допускающее нажатие:
Снова нужен доступ к кнопке в методе the_button_was_clicked, поэтому сохраняем ссылку на неё в self. Чтобы поменять текст кнопки, передаём str в .setText(). Чтобы отключить кнопку, вызываем .setEnabled() с аргументом False. И запускаем программу. Если нажать на кнопку, текст изменится и кнопка станет недоступной.
В методах слота можно не только менять кнопку, которая активирует сигнал, но и делать всё что угодно. Например, поменять заголовок окна, добавив в метод the_button_was_clicked эту строку:
Большинство виджетов, в том числе QMainWindow, имеют свои сигналы. В следующем, более сложном примере подключим сигнал .windowTitleChanged в QMainWindow к пользовательскому методу слота. А также сделаем для этого слота новый заголовок окна:
Сначала создаём список заголовков окна и выбираем один из них наугад, используя встроенную функцию Python random.choice(). Подключаем пользовательский метод слота the_window_title_changed к сигналу окна .windowTitleChanged.
При нажатии на кнопку заголовок окна случайным образом изменится. Если новый заголовок окна изменится на Something went wrong («Что-то пошло не так»), кнопка отключится.
Запускаем! Нажимайте на кнопку, пока заголовок не изменится на Something went wrong. В этом примере стоит обратить внимание вот на что:
Сигнал windowTitleChanged при установке заголовка окна выдаётся не всегда. Он срабатывает, только если новый заголовок отличается от предыдущего: если один и тот же заголовок устанавливается несколько раз, сигнал срабатывает только в первый раз. Чтобы избежать неожиданностей, важно перепроверять условия срабатывания сигналов при их использовании в приложении.
С помощью сигналов создаются цепочки. Одно событие — нажатие кнопки — может привести к тому, что поочерёдно произойдут другие. Эти последующие эффекты отделены от того, что их вызвало. Они возникают согласно простым правилам. И это отделение эффектов от их триггеров — один из ключевых принципов, которые учитываются при создании приложений с графическим интерфейсом. Возвращаться к этому будем на протяжении всего курса.
Мы рассмотрели сигналы и слоты, показали простые сигналы и их использование для передачи данных и состояния в приложении. Теперь переходим к виджетам Qt, которые будут использоваться в приложениях вместе с сигналами.
Подключение виджетов друг к другу напрямую
Мы уже видели примеры подключения сигналов виджетов к методам Python. Когда сигнал из виджета срабатывает, вызывается метод Python, из сигнала он получает данные. Но для обработки сигналов не всегда нужна функция Python — можно подключать виджеты друг к другу напрямую.
Добавим в окно виджеты QLineEdit и QLabel. В __init__ для окна и подключим сигнал редактирования строки .textChanged к методу .setText в QLabel. Когда в QLineEdit меняется текст, он сразу будет поступать в QLabel (в метод .setText):
Внимание: чтобы подключить входные данные к метке, нужно определить и эти данные, и метку. В этом коде в макет добавляются два виджета и устанавливаются в окне. Подробно рассмотрим макеты позже, а пока не обращайте на них внимания.

Введите текст в верхнем поле — он сразу появится в виде метки.
У большинства виджетов Qt есть доступные слоты, к которым подключается любой сигнал, возврощающий тот же тип, что он принимает. В документации по виджетам, в разделе Public Slots («Общедоступные слоты»), имеются слоты для каждого виджета. Посмотрите документацию для QLabel.
События
Любое взаимодействие пользователя с приложением Qt — это событие. Есть много типов событий, каждое из которых — это отдельный тип взаимодействия. В Qt события представлены объектами событий, в которые упакована информация о произошедшем. События передаются определённым обработчикам событий в виджете, где произошло взаимодействие.
Определяя пользовательские или расширенные обработчики событий, можно менять способ реагирования виджетов на них. Обработчики событий определяются так же, как и любой другой метод, но название обработчика зависит от типа обрабатываемого события.
QMouseEvent — одно из основных событий, получаемых виджетами. События QMouseEvent создаются для каждого отдельного нажатия кнопки мыши и её перемещения в виджете. Вот обработчики событий мыши:
QApplication¶
Displays a simple message box about Qt. The message includes the version number of Qt being used by the application.
This is useful for inclusion in the Help menu of an application, as shown in the Menus example.
This function is a convenience slot for QMessageBox.aboutQt() .
static PySide.QtGui.QApplication.activeModalWidget()¶
| Return type: | PySide.QtGui.QWidget |
|---|
Returns the active modal widget.
A modal widget is a special top-level widget which is a subclass of PySide.QtGui.QDialog that specifies the modal parameter of the constructor as true. A modal widget must be closed before the user can continue with other parts of the program.
Modal widgets are organized in a stack. This function returns the active modal widget at the top of the stack.
static PySide.QtGui.QApplication.activePopupWidget()¶
| Return type: | PySide.QtGui.QWidget |
|---|
Returns the active popup widget.
A popup widget is a special top-level widget that sets the Qt::WType_Popup widget flag, e.g. the PySide.QtGui.QMenu widget. When the application opens a popup widget, all events are sent to the popup. Normal widgets and modal widgets cannot be accessed before the popup widget is closed.
Only other popup widgets may be opened when a popup widget is shown. The popup widgets are organized in a stack. This function returns the active popup widget at the top of the stack.
static PySide.QtGui.QApplication.activeWindow()¶
| Return type: | PySide.QtGui.QWidget |
|---|
Returns the application top-level window that has the keyboard input focus, or 0 if no application window has the focus. There might be an PySide.QtGui.QApplication.activeWindow() even if there is no PySide.QtGui.QApplication.focusWidget() , for example if no widget in that window accepts key events.
- widget – PySide.QtGui.QWidget
- duration – PySide.QtCore.int
Causes an alert to be shown for widget if the window is not the active window. The alert is shown for msec miliseconds. If msec is zero (the default), then the alert is shown indefinitely until the window becomes active again.
Currently this function does nothing on Qt for Embedded Linux.
On Mac OS X, this works more at the application level and will cause the application icon to bounce in the dock.
On Windows, this causes the window’s taskbar entry to flash for a time. If msec is zero, the flashing will stop and the taskbar entry will turn a different color (currently orange).
On X11, this will cause the window to be marked as “demands attention”, the window must not be hidden (i.e. not have hide() called on it, but be visible in some sort of way) in order for this to work.
static PySide.QtGui.QApplication.allWidgets()¶
| Return type: |
|---|
Returns a list of all the widgets in the application.
The list is empty ( QList.isEmpty() ) if there are no widgets.
Some of the widgets may be hidden.
PySide.QtGui.QApplication.autoSipEnabled()¶
| Return type: | PySide.QtCore.bool |
|---|
This property holds toggles automatic SIP (software input panel) visibility.
Set this property to true to automatically display the SIP when entering widgets that accept keyboard input. This property only affects widgets with the WA_InputMethodEnabled attribute set, and is typically used to launch a virtual keyboard on devices which have very few or no keys.
The property only has an effect on platforms which use software input panels, such as Windows CE and Symbian.
The default is platform dependent.
Sounds the bell, using the default volume and sound. The function is not available in Qt for Embedded Linux.
static PySide.QtGui.QApplication.changeOverrideCursor(arg__1)¶
| Parameters: | arg__1 – PySide.QtGui.QCursor |
|---|
Changes the currently active application override cursor to cursor .
static PySide.QtGui.QApplication.clipboard()¶
| Return type: | PySide.QtGui.QClipboard |
|---|
Returns a pointer to the application global clipboard.
The PySide.QtGui.QApplication object should already be constructed before accessing the clipboard.
Closes all top-level windows.
This function is particularly useful for applications with many top-level windows. It could, for example, be connected to a Exit entry in the File menu:
The windows are closed in random order, until one window does not accept the close event. The application quits when the last window was successfully closed; this can be turned off by setting PySide.QtGui.QApplication.quitOnLastWindowClosed() to false.
static PySide.QtGui.QApplication.colorSpec()¶
| Return type: | PySide.QtCore.int |
|---|
Returns the color specification.
PySide.QtGui.QApplication.commitData(sm)¶
| Parameters: | sm – PySide.QtGui.QSessionManager |
|---|
This function deals with session management . It is invoked when the PySide.QtGui.QSessionManager wants the application to commit all its data.
Usually this means saving all open files, after getting permission from the user. Furthermore you may want to provide a means by which the user can cancel the shutdown.
You should not exit the application within this function. Instead, the session manager may or may not do this afterwards, depending on the context.
Within this function, no user interaction is possible, unless you ask the manager for explicit permission. See QSessionManager.allowsInteraction() and QSessionManager.allowsErrorInteraction() for details and example usage.
The default implementation requests interaction and sends a close event to all visible top-level widgets. If any event was rejected, the shutdown is canceled.
PySide.QtGui.QApplication.commitDataRequest(sessionManager)¶
| Parameters: | sessionManager – PySide.QtGui.QSessionManager |
|---|
static PySide.QtGui.QApplication.cursorFlashTime()¶
| Return type: | PySide.QtCore.int |
|---|
This property holds the text cursor’s flash (blink) time in milliseconds.
The flash time is the time required to display, invert and restore the caret display. Usually the text cursor is displayed for half the cursor flash time, then hidden for the same amount of time, but this may vary.
The default value on X11 is 1000 milliseconds. On Windows, the Control Panel value is used and setting this property sets the cursor flash time for all applications.
We recommend that widgets do not cache this value as it may change at any time if the user changes the global desktop settings.
static PySide.QtGui.QApplication.desktop()¶
| Return type: | PySide.QtGui.QDesktopWidget |
|---|
Returns the desktop widget (also called the root window).
The desktop may be composed of multiple screens, so it would be incorrect, for example, to attempt to center some widget in the desktop’s geometry. PySide.QtGui.QDesktopWidget has various functions for obtaining useful geometries upon the desktop, such as QDesktopWidget.screenGeometry() and QDesktopWidget.availableGeometry() .
On X11, it is also possible to draw on the desktop.
static PySide.QtGui.QApplication.desktopSettingsAware()¶
| Return type: | PySide.QtCore.bool |
|---|
Returns true if Qt is set to use the system’s standard colors, fonts, etc.; otherwise returns false. The default is true.
static PySide.QtGui.QApplication.doubleClickInterval()¶
| Return type: | PySide.QtCore.int |
|---|
This property holds the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used. However, on Windows and Symbian OS, calling this function sets the double click interval for all applications.
- old – PySide.QtGui.QWidget
- now – PySide.QtGui.QWidget
Returns the application widget that has the keyboard input focus, or 0 if no widget in this application has the focus.
static PySide.QtGui.QApplication.font(className)¶
| Parameters: | className – str |
|---|---|
| Return type: | PySide.QtGui.QFont |
This is an overloaded function.
Returns the font for widgets of the given className .
static PySide.QtGui.QApplication.font(arg__1)
| Parameters: | arg__1 – PySide.QtGui.QWidget |
|---|---|
| Return type: | PySide.QtGui.QFont |
This is an overloaded function.
Returns the default font for the widget .
static PySide.QtGui.QApplication.font()
| Return type: | PySide.QtGui.QFont |
|---|
Returns the default application font.
PySide.QtGui.QApplication.fontDatabaseChanged()¶ static PySide.QtGui.QApplication.fontMetrics()¶
| Return type: | PySide.QtGui.QFontMetrics |
|---|
Returns display (screen) font metrics for the application font.
static PySide.QtGui.QApplication.globalStrut()¶
| Return type: | PySide.QtCore.QSize |
|---|
This property holds the minimum size that any GUI element that the user can interact with should have.
For example, no button should be resized to be smaller than the global strut size. The strut size should be considered when reimplementing GUI controls that may be used on touch-screens or similar I/O devices.
By default, this property contains a PySide.QtCore.QSize object with zero width and height.
PySide.QtGui.QApplication.inputContext()¶
| Return type: | PySide.QtGui.QInputContext |
|---|
Returns the PySide.QtGui.QInputContext instance used by the application.
static PySide.QtGui.QApplication.isEffectEnabled(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.Qt.UIEffect |
|---|---|
| Return type: | PySide.QtCore.bool |
static PySide.QtGui.QApplication.isLeftToRight()¶
| Return type: | PySide.QtCore.bool |
|---|
Returns true if the application’s layout direction is Qt.LeftToRight ; otherwise returns false.
static PySide.QtGui.QApplication.isRightToLeft()¶
| Return type: | PySide.QtCore.bool |
|---|
Returns true if the application’s layout direction is Qt.RightToLeft ; otherwise returns false.
PySide.QtGui.QApplication.isSessionRestored()¶
| Return type: | PySide.QtCore.bool |
|---|
Returns true if the application has been restored from an earlier session ; otherwise returns false.
static PySide.QtGui.QApplication.keyboardInputDirection()¶
| Return type: | PySide.QtCore.Qt.LayoutDirection |
|---|
Returns the current keyboard input direction.
static PySide.QtGui.QApplication.keyboardInputInterval()¶
| Return type: | PySide.QtCore.int |
|---|
This property holds the time limit in milliseconds that distinguishes a key press from two consecutive key presses.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used.
static PySide.QtGui.QApplication.keyboardInputLocale()¶
| Return type: | PySide.QtCore.QLocale |
|---|
Returns the current keyboard input locale.
static PySide.QtGui.QApplication.keyboardModifiers()¶
| Return type: | PySide.QtCore.Qt.KeyboardModifiers |
|---|
Returns the current state of the modifier keys on the keyboard. The current state is updated sychronously as the event queue is emptied of events that will spontaneously change the keyboard state ( QEvent.KeyPress and QEvent.KeyRelease events).
It should be noted this may not reflect the actual keys held on the input device at the time of calling but rather the modifiers as last reported in one of the above events. If no keys are being held Qt.NoModifier is returned.
PySide.QtGui.QApplication.lastWindowClosed()¶ static PySide.QtGui.QApplication.layoutDirection()¶
| Return type: | PySide.QtCore.Qt.LayoutDirection |
|---|
This property holds the default layout direction for this application.
On system start-up, the default layout direction depends on the application’s language.
static PySide.QtGui.QApplication.mouseButtons()¶
| Return type: | PySide.QtCore.Qt.MouseButtons |
|---|
Returns the current state of the buttons on the mouse. The current state is updated syncronously as the event queue is emptied of events that will spontaneously change the mouse state ( QEvent.MouseButtonPress and QEvent.MouseButtonRelease events).
It should be noted this may not reflect the actual buttons held on the input device at the time of calling but rather the mouse buttons as last reported in one of the above events. If no mouse buttons are being held Qt.NoButton is returned.
static PySide.QtGui.QApplication.overrideCursor()¶
| Return type: | PySide.QtGui.QCursor |
|---|
Returns the active application override cursor.
This function returns 0 if no application cursor has been defined (i.e. the internal cursor stack is empty).
static PySide.QtGui.QApplication.palette(arg__1)¶
| Parameters: | arg__1 – PySide.QtGui.QWidget |
|---|---|
| Return type: | PySide.QtGui.QPalette |
This is an overloaded function.
If a widget is passed, the default palette for the widget’s class is returned. This may or may not be the application palette. In most cases there is no special palette for certain types of widgets, but one notable exception is the popup menu under Windows, if the user has defined a special background color for menus in the display settings.
static PySide.QtGui.QApplication.palette(className)
| Parameters: | className – str |
|---|---|
| Return type: | PySide.QtGui.QPalette |
This is an overloaded function.
Returns the palette for widgets of the given className .
static PySide.QtGui.QApplication.palette()
| Return type: | PySide.QtGui.QPalette |
|---|
Returns the application palette.
static PySide.QtGui.QApplication.queryKeyboardModifiers()¶
| Return type: | PySide.QtCore.Qt.KeyboardModifiers |
|---|
Queries and returns the state of the modifier keys on the keyboard. Unlike keyboardModifiers, this method returns the actual keys held on the input device at the time of calling the method.
It does not rely on the keypress events having been received by this process, which makes it possible to check the modifiers while moving a window, for instance. Note that in most cases, you should use PySide.QtGui.QApplication.keyboardModifiers() , which is faster and more accurate since it contains the state of the modifiers as they were when the currently processed event was received.
static PySide.QtGui.QApplication.quitOnLastWindowClosed()¶
| Return type: | PySide.QtCore.bool |
|---|
This property holds whether the application implicitly quits when the last window is closed..
The default is true.
If this property is true, the applications quits when the last visible primary window (i.e. window with no parent) with the Qt.WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except for sub-windows. Refer to Qt.WindowType for a detailed list of Qt.Window objects.
If PySide.QtGui.QApplication.setOverrideCursor() has been called twice, calling PySide.QtGui.QApplication.restoreOverrideCursor() will activate the first cursor set. Calling this function a second time restores the original widgets’ cursors.
PySide.QtGui.QApplication.saveState(sm)¶
| Parameters: | sm – PySide.QtGui.QSessionManager |
|---|
This function deals with session management . It is invoked when the session manager wants the application to preserve its state for a future session.
For example, a text editor would create a temporary file that includes the current contents of its edit buffers, the location of the cursor and other aspects of the current editing session.
You should never exit the application within this function. Instead, the session manager may or may not do this afterwards, depending on the context. Futhermore, most session managers will very likely request a saved state immediately after the application has been started. This permits the session manager to learn about the application’s restart policy.
Within this function, no user interaction is possible, unless you ask the manager for explicit permission. See QSessionManager.allowsInteraction() and QSessionManager.allowsErrorInteraction() for details.
PySide.QtGui.QApplication.saveStateRequest(sessionManager)¶
| Parameters: | sessionManager – PySide.QtGui.QSessionManager |
|---|
PySide.QtGui.QApplication.sessionId()¶
| Return type: | unicode |
|---|
Returns the current session’s identifier.
If the application has been restored from an earlier session, this identifier is the same as it was in that previous session. The session identifier is guaranteed to be unique both for different applications and for different instances of the same application.
PySide.QtGui.QApplication.sessionKey()¶
| Return type: | unicode |
|---|
Returns the session key in the current session .
If the application has been restored from an earlier session, this key is the same as it was when the previous session ended.
static PySide.QtGui.QApplication.setActiveWindow(act)¶
| Parameters: | act – PySide.QtGui.QWidget |
|---|
Sets the active window to the active widget in response to a system event. The function is called from the platform specific event handlers.
This function does not set the keyboard focus to the active widget. Call QWidget.activateWindow() instead.
It sets the PySide.QtGui.QApplication.activeWindow() and PySide.QtGui.QApplication.focusWidget() attributes and sends proper WindowActivate / WindowDeactivate and FocusIn / FocusOut events to all appropriate widgets. The window will then be painted in active state (e.g. cursors in line edits will blink), and it will have tool tips enabled.
PySide.QtGui.QApplication.setAutoSipEnabled(enabled)¶
| Parameters: | enabled – PySide.QtCore.bool |
|---|
This property holds toggles automatic SIP (software input panel) visibility.
Set this property to true to automatically display the SIP when entering widgets that accept keyboard input. This property only affects widgets with the WA_InputMethodEnabled attribute set, and is typically used to launch a virtual keyboard on devices which have very few or no keys.
The property only has an effect on platforms which use software input panels, such as Windows CE and Symbian.
The default is platform dependent.
static PySide.QtGui.QApplication.setColorSpec(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.int |
|---|
Sets the color specification for the application to spec .
The color specification controls how the application allocates colors when run on a display with a limited amount of colors, e.g. 8 bit / 256 color displays.
The color specification must be set before you create the PySide.QtGui.QApplication object.
The options are:
Be aware that the CustomColor and ManyColor choices may lead to colormap flashing: The foreground application gets (most) of the available colors, while the background windows will look less attractive.
static PySide.QtGui.QApplication.setCursorFlashTime(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.int |
|---|
This property holds the text cursor’s flash (blink) time in milliseconds.
The flash time is the time required to display, invert and restore the caret display. Usually the text cursor is displayed for half the cursor flash time, then hidden for the same amount of time, but this may vary.
The default value on X11 is 1000 milliseconds. On Windows, the Control Panel value is used and setting this property sets the cursor flash time for all applications.
We recommend that widgets do not cache this value as it may change at any time if the user changes the global desktop settings.
static PySide.QtGui.QApplication.setDesktopSettingsAware(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.bool |
|---|
Sets whether Qt should use the system’s standard colors, fonts, etc., to on . By default, this is true.
This function must be called before creating the PySide.QtGui.QApplication object, like this:
static PySide.QtGui.QApplication.setDoubleClickInterval(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.int |
|---|
This property holds the time limit in milliseconds that distinguishes a double click from two consecutive mouse clicks.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used. However, on Windows and Symbian OS, calling this function sets the double click interval for all applications.
- arg__1 – PySide.QtCore.Qt.UIEffect
- enable – PySide.QtCore.bool
- arg__1 – PySide.QtGui.QFont
- className – str
Changes the default application font to font . If className is passed, the change applies only to classes that inherit className (as reported by QObject.inherits() ).
On application start-up, the default font depends on the window system. It can vary depending on both the window system version and the locale. This function lets you override the default font; but overriding may be a bad idea because, for example, some locales need extra large fonts to support their special characters.
Do not use this function in conjunction with Qt Style Sheets . The font of an application can be customized using the “font” style sheet property. To set a bold font for all QPushButtons, set the application PySide.QtGui.QApplication.styleSheet() as ” PySide.QtGui.QPushButton < font: bold >”
static PySide.QtGui.QApplication.setGlobalStrut(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.QSize |
|---|
This property holds the minimum size that any GUI element that the user can interact with should have.
For example, no button should be resized to be smaller than the global strut size. The strut size should be considered when reimplementing GUI controls that may be used on touch-screens or similar I/O devices.
By default, this property contains a PySide.QtCore.QSize object with zero width and height.
static PySide.QtGui.QApplication.setGraphicsSystem(arg__1)¶
| Parameters: | arg__1 – unicode |
|---|
Sets the default graphics backend to system , which will be used for on-screen widgets and QPixmaps. The available systems are "native" , "raster" and "opengl" .
There are several ways to set the graphics backend, in order of decreasing precedence:
- the application commandline -graphicssystem switch
- the QT_GRAPHICSSYSTEM environment variable
- the Qt configure -graphicssystem switch
If the highest precedence switch sets an invalid name, the error will be ignored and the default backend will be used.
This function is only effective before the PySide.QtGui.QApplication constructor is called.
The "opengl" option is currently experimental.
PySide.QtGui.QApplication.setInputContext(arg__1)¶
| Parameters: | arg__1 – PySide.QtGui.QInputContext |
|---|
This function replaces the PySide.QtGui.QInputContext instance used by the application with inputContext .
Qt takes ownership of the given inputContext .
static PySide.QtGui.QApplication.setKeyboardInputInterval(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.int |
|---|
This property holds the time limit in milliseconds that distinguishes a key press from two consecutive key presses.
The default value on X11 is 400 milliseconds. On Windows and Mac OS, the operating system’s value is used.
static PySide.QtGui.QApplication.setLayoutDirection(direction)¶
| Parameters: | direction – PySide.QtCore.Qt.LayoutDirection |
|---|
This property holds the default layout direction for this application.
On system start-up, the default layout direction depends on the application’s language.
static PySide.QtGui.QApplication.setOverrideCursor(arg__1)¶
| Parameters: | arg__1 – PySide.QtGui.QCursor |
|---|
Sets the application override cursor to cursor .
Application override cursors are intended for showing the user that the application is in a special state, for example during an operation that might take some time.
Application cursors are stored on an internal stack. PySide.QtGui.QApplication.setOverrideCursor() pushes the cursor onto the stack, and PySide.QtGui.QApplication.restoreOverrideCursor() pops the active cursor off the stack. PySide.QtGui.QApplication.changeOverrideCursor() changes the curently active application override cursor.
- arg__1 – PySide.QtGui.QPalette
- className – str
Changes the default application palette to palette .
If className is passed, the change applies only to widgets that inherit className (as reported by QObject.inherits() ). If className is left 0, the change affects all widgets, thus overriding any previously set class specific palettes.
The palette may be changed according to the current GUI style in QStyle.polish() .
Do not use this function in conjunction with Qt Style Sheets . When using style sheets, the palette of a widget can be customized using the “color”, “background-color”, “selection-color”, “selection-background-color” and “alternate-background-color”.
Some styles do not use the palette for all drawing, for instance, if they make use of native theme engines. This is the case for the Windows XP, Windows Vista, and Mac OS X styles.
static PySide.QtGui.QApplication.setQuitOnLastWindowClosed(quit)¶
| Parameters: | quit – PySide.QtCore.bool |
|---|
This property holds whether the application implicitly quits when the last window is closed..
The default is true.
If this property is true, the applications quits when the last visible primary window (i.e. window with no parent) with the Qt.WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except for sub-windows. Refer to Qt.WindowType for a detailed list of Qt.Window objects.
static PySide.QtGui.QApplication.setStartDragDistance(l)¶
| Parameters: | l – PySide.QtCore.int |
|---|
If you support drag and drop in your application, and want to start a drag and drop operation after the user has moved the cursor a certain distance with a button held down, you should use this property’s value as the minimum distance required.
For example, if the mouse position of the click is stored in startPos and the current position (e.g. in the mouse move event) is currentPos , you can find out if a drag should be started with code like this:
The default value is 4 pixels.
static PySide.QtGui.QApplication.setStartDragTime(ms)¶
| Parameters: | ms – PySide.QtCore.int |
|---|
This property holds the time in milliseconds that a mouse button must be held down before a drag and drop operation will begin.
If you support drag and drop in your application, and want to start a drag and drop operation after the user has held down a mouse button for a certain amount of time, you should use this property’s value as the delay.
Qt also uses this delay internally, e.g. in PySide.QtGui.QTextEdit and PySide.QtGui.QLineEdit , for starting a drag.
The default value is 500 ms.
static PySide.QtGui.QApplication.setStyle(arg__1)¶
| Parameters: | arg__1 – unicode |
|---|---|
| Return type: | PySide.QtGui.QStyle |
This is an overloaded function.
The string must be one of the QStyleFactory.keys() , typically one of “windows”, “motif”, “cde”, “plastique”, “windowsxp”, or “macintosh”. Style names are case insensitive.
Returns 0 if an unknown style is passed, otherwise the PySide.QtGui.QStyle object returned is set as the application’s GUI style.
To ensure that the application’s style is set correctly, it is best to call this function before the PySide.QtGui.QApplication constructor, if possible.
static PySide.QtGui.QApplication.setStyle(arg__1)
| Parameters: | arg__1 – PySide.QtGui.QStyle |
|---|
Sets the application’s GUI style to style . Ownership of the style object is transferred to PySide.QtGui.QApplication , so PySide.QtGui.QApplication will delete the style object on application exit or when a new style is set and the old style is still the parent of the application object.
When switching application styles, the color palette is set back to the initial colors or the system defaults. This is necessary since certain styles have to adapt the color palette to be fully style-guide compliant.
Setting the style before a palette has been set, i.e., before creating PySide.QtGui.QApplication , will cause the application to use QStyle.standardPalette() for the palette.
Qt style sheets are currently not supported for custom PySide.QtGui.QStyle subclasses. We plan to address this in some future release.
PySide.QtGui.QApplication.setStyleSheet(sheet)¶
| Parameters: | sheet – unicode |
|---|
This property holds the application style sheet.
By default, this property returns an empty string unless the user specifies the -stylesheet option on the command line when running the application.
static PySide.QtGui.QApplication.setWheelScrollLines(arg__1)¶
| Parameters: | arg__1 – PySide.QtCore.int |
|---|
This property holds the number of lines to scroll a widget, when the mouse wheel is rotated..
If the value exceeds the widget’s number of visible lines, the widget should interpret the scroll operation as a single page up or page down . If the widget is an item view class , then the result of scrolling one line depends on the setting of the widget’s scroll mode . Scroll one line can mean scroll one item or scroll one pixel .
By default, this property has a value of 3.
static PySide.QtGui.QApplication.setWindowIcon(icon)¶
| Parameters: | icon – PySide.QtGui.QIcon |
|---|
This property holds the default window icon.
static PySide.QtGui.QApplication.startDragDistance()¶
| Return type: | PySide.QtCore.int |
|---|
If you support drag and drop in your application, and want to start a drag and drop operation after the user has moved the cursor a certain distance with a button held down, you should use this property’s value as the minimum distance required.
For example, if the mouse position of the click is stored in startPos and the current position (e.g. in the mouse move event) is currentPos , you can find out if a drag should be started with code like this:
The default value is 4 pixels.
static PySide.QtGui.QApplication.startDragTime()¶
| Return type: | PySide.QtCore.int |
|---|
This property holds the time in milliseconds that a mouse button must be held down before a drag and drop operation will begin.
If you support drag and drop in your application, and want to start a drag and drop operation after the user has held down a mouse button for a certain amount of time, you should use this property’s value as the delay.
Qt also uses this delay internally, e.g. in PySide.QtGui.QTextEdit and PySide.QtGui.QLineEdit , for starting a drag.
The default value is 500 ms.
static PySide.QtGui.QApplication.style()¶
| Return type: | PySide.QtGui.QStyle |
|---|
Returns the application’s style object.
PySide.QtGui.QApplication.styleSheet()¶
| Return type: | unicode |
|---|
This property holds the application style sheet.
By default, this property returns an empty string unless the user specifies the -stylesheet option on the command line when running the application.
Synchronizes with the X server in the X11 implementation. This normally takes some time. Does nothing on other platforms.
- x – PySide.QtCore.int
- y – PySide.QtCore.int
This is an overloaded function.
Returns the top-level widget at the point ( x , y ); returns 0 if there is no such widget.
static PySide.QtGui.QApplication.topLevelAt(p)
| Parameters: | p – PySide.QtCore.QPoint |
|---|---|
| Return type: | PySide.QtGui.QWidget |
Returns the top-level widget at the given point ; returns 0 if there is no such widget.
static PySide.QtGui.QApplication.topLevelWidgets()¶
| Return type: |
|---|
Returns a list of the top-level widgets (windows) in the application.
Some of the top-level widgets may be hidden, for example a tooltip if no tooltip is currently shown.
static PySide.QtGui.QApplication.type()¶
| Return type: | PySide.QtGui.QApplication.Type |
|---|
Returns the type of application ( Tty , GuiClient , or GuiServer ). The type is set when constructing the PySide.QtGui.QApplication object.
static PySide.QtGui.QApplication.wheelScrollLines()¶
| Return type: | PySide.QtCore.int |
|---|
This property holds the number of lines to scroll a widget, when the mouse wheel is rotated..
If the value exceeds the widget’s number of visible lines, the widget should interpret the scroll operation as a single page up or page down . If the widget is an item view class , then the result of scrolling one line depends on the setting of the widget’s scroll mode . Scroll one line can mean scroll one item or scroll one pixel .
By default, this property has a value of 3.
- x – PySide.QtCore.int
- y – PySide.QtCore.int
This is an overloaded function.
Returns the widget at global screen position ( x , y ), or 0 if there is no Qt widget there.
static PySide.QtGui.QApplication.widgetAt(p)
| Parameters: | p – PySide.QtCore.QPoint |
|---|---|
| Return type: | PySide.QtGui.QWidget |
Returns the widget at global screen position point , or 0 if there is no Qt widget there.