### PyQt5 Configuration File Example
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/installation.html
An example of a PyQt5 configuration file used with the `configure.py` script. This file defines Python installation details, PyQt installation paths, and specific Qt module configurations. It demonstrates variable substitution and section definitions for different Qt versions.
```ini
# The target Python installation.
py_platform = linux
py_inc_dir = %(sysroot)/usr/include/python%(py_major).%(py_minor)
py_pylib_dir = %(sysroot)/usr/lib/python%(py_major).%(py_minor)/config
py_pylib_lib = python%(py_major).%(py_minor)mu
# The target PyQt installation.
pyqt_module_dir = %(sysroot)/usr/lib/python%(py_major)/dist-packages
pyqt_bin_dir = %(sysroot)/usr/bin
pyqt_sip_dir = %(sysroot)/usr/share/sip/PyQt5
pyuic_interpreter = /usr/bin/python%(py_major).%(py_minor)
pyqt_disabled_features = PyQt_Desktop_OpenGL PyQt_qreal_double
# Qt configuration common to all versions.
qt_shared = True
[Qt 5.1]
pyqt_modules = QtCore QtDBus QtDesigner QtGui QtHelp QtMultimedia
QtMultimediaWidgets QtNetwork QtOpenGL QtPrintSupport QtQml QtQuick
QtSensors QtSerialPort QtSql QtSvg QtTest QtWebKit QtWebKitWidgets
QtWidgets QtXmlPatterns _QOpenGLFunctions_ES2
```
--------------------------------
### Install PyQt5 GPL Version using pip
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/installation.txt
Installs the GPL version of PyQt5 using pip. This command downloads and installs the pre-built wheel from the Python Package Index. It automatically includes necessary parts of the Qt library and the 'sip' package. This method is recommended for Python v3.5 and later.
```bash
pip3 install pyqt5
```
--------------------------------
### PyQt5 Application Entry Point with QApplication
Source: https://context7.com/baoboa/pyqt5/llms.txt
Demonstrates the essential setup for a PyQt5 GUI application. It initializes the QApplication, creates a main window (QWidget), adds a QLabel, and starts the application's event loop. This is the fundamental structure for any PyQt5 application.
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
# Create the application instance (must be first)
app = QApplication(sys.argv)
# Create main window
window = QWidget()
window.setWindowTitle("My First PyQt5 App")
window.setGeometry(100, 100, 400, 300) # x, y, width, height
# Add a label
layout = QVBoxLayout()
label = QLabel("Hello, PyQt5!")
layout.addWidget(label)
window.setLayout(layout)
# Show window and run event loop
window.show()
sys.exit(app.exec_()) # Returns exit code when app closes
```
--------------------------------
### Initialize Documentation Options - JavaScript
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api/qhelpenginecore.html
Initializes documentation options for a web-based reference guide. This includes settings like URL root, version, and file suffixes. It is a configuration object used by the documentation system.
```javascript
var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '5.8.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' };
```
--------------------------------
### Initialize QTcpServer in PyQt
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api/qtcpserver.html
Demonstrates the basic initialization of a QTcpServer object in PyQt. This is the starting point for creating a TCP server that can listen for incoming connections.
```python
from PyQt5.QtNetwork import QTcpServer
server = QTcpServer()
```
--------------------------------
### pyqtlicense Help Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Displays a help message for the 'pyqtlicense' tool, outlining its usage and available command-line options.
```bash
pyqtlicense -h
```
--------------------------------
### pyqtlicense Qt Installation Directory Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Specifies the directory of the LGPL or commercial Qt installation to be included in the licensed wheel. This is a mandatory option.
```bash
pyqtlicense --qt
```
--------------------------------
### pyqtlicense Verbose Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Displays additional progress messages during the wheel generation process.
```bash
pyqtlicense --verbose
```
--------------------------------
### Example: Connecting Overloaded Signals
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/signals_slots.rst.txt
Illustrates how to connect to specific overloads of a signal when multiple C++ signatures exist.
```APIDOC
## Example: Connecting Overloaded Signals
### Description
This code demonstrates the connection of overloaded signals, showing how to specify which overload to connect to.
### Method
`connect_activated()`
`handle_int(index)`
`handle_string(text)`
### Endpoint
N/A (This is a class method example)
### Parameters
N/A
### Request Example
```python
from PyQt5.QtWidgets import QComboBox
class Bar(QComboBox):
def connect_activated(self):
# The PyQt5 documentation will define what the default overload is.
# In this case it is the overload with the single integer argument.
self.activated.connect(self.handle_int)
# For non-default overloads we have to specify which we want to
# connect. In this case the one with the single string argument.
# (Note that we could also explicitly specify the default if we
# wanted to.)
self.activated[str].connect(self.handle_string)
def handle_int(self, index):
print("activated signal passed integer", index)
def handle_string(self, text):
print("activated signal passed QString", text)
bar_instance = Bar()
# Assume bar_instance is populated and an item is activated
# bar_instance.connect_activated()
```
### Response
#### Success Response (200)
Prints messages to the console indicating whether the `handle_int` or `handle_string` slot was called based on the activated item's type.
#### Response Example
```
activated signal passed integer 5
```
OR
```
activated signal passed QString "Some Text"
```
```
--------------------------------
### pyqtlicense Output Directory Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Specifies the directory where the generated licensed wheel will be saved.
```bash
pyqtlicense --output
```
--------------------------------
### Directly Use Generated UI Code in PyQt5
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/designer.txt
This example shows the direct approach to using generated UI code. It creates a QApplication, a QDialog, instantiates the Ui_ImageDialog class, and calls setupUi to set up the user interface on the dialog. Finally, it shows the dialog and starts the application's event loop.
```python
import sys
from PyQt5.QtWidgets import QApplication, QDialog
from ui_imagedialog import Ui_ImageDialog
app = QApplication(sys.argv)
window = QDialog()
ui = Ui_ImageDialog()
ui.setupUi(window)
window.show()
sys.exit(app.exec_())
```
--------------------------------
### Documentation Options Configuration - JavaScript
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api_details/qjsonobject.html
Configures documentation options for the PyQt 5.7.1 reference guide. This JavaScript object sets variables like URL root, version, and file suffix for the documentation.
```javascript
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '5.7.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
```
--------------------------------
### Generate Licensed PyQt5 Wheel using pyqtlicense
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/installation.txt
Generates a licensed wheel for the commercial version of PyQt5. This command requires an unlicensed wheel, a license file, and the path to a Qt installation. It creates a distributable wheel that includes the necessary Qt components.
```bash
pyqtlicense --license --qt
```
--------------------------------
### pyqtlicense Version Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Displays the version number of the 'pyqtlicense' tool.
```bash
pyqtlicense -V
```
--------------------------------
### Initialize Documentation Options (JavaScript)
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api/qcommonstyle.html
Initializes documentation options for the project, including root URL, version, file suffix, and source link suffix. This is a common pattern in Sphinx-generated documentation.
```javascript
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '5.8.2',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
```
--------------------------------
### pyqtlicense Build Tag Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Specifies a custom build tag for the generated wheel name. An empty string omits the build tag.
```bash
pyqtlicense --build-tag
```
--------------------------------
### pyqtlicense Qt Version Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Specifies the 3-part version number of the Qt installation. If not provided, it's extracted from the --qt option.
```bash
pyqtlicense --qt-version
```
--------------------------------
### pyqtlicense Wheel Qt Version Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Specifies the 3-part version number of the Qt installation that the wheel was built against. If not provided, it's extracted from the wheel filename.
```bash
pyqtlicense --wheel-qt-version
```
--------------------------------
### PyQt5 Cooperative Multi-inheritance Example
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/pyqt4_differences.rst.txt
Demonstrates the correct way to implement cooperative multi-inheritance in PyQt5 using super().__init__(**kwds). This ensures that mixin classes also correctly handle initialization and pass keyword arguments.
```python
class MyQObject(QObject, MyMixin):
def __init__(self, **kwds):
super().__init__(**kwds)
# Other initialisation...
class MyMixin:
def __init__(self, mixin_arg, **kwds):
super().__init__(**kwds)
# Other initialisation...
```
--------------------------------
### pyqtlicense OpenSSL Directory Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Replace OpenSSL DLLs in the unlicensed wheel with those found in the specified directory.
```bash
pyqtlicense --openssl
```
--------------------------------
### Define and Emit a Simple Signal in PyQt5
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/signals_slots.txt
Shows how to define a signal without arguments, connect it to a slot, and then emit the signal. This example illustrates the basic workflow of signal-slot communication in PyQt5.
```python
from PyQt5.QtCore import QObject, pyqtSignal
class Foo(QObject):
# Define a new signal called 'trigger' that has no arguments.
trigger = pyqtSignal()
def connect_and_emit_trigger(self):
# Connect the trigger signal to a slot.
self.trigger.connect(self.handle_trigger)
# Emit the signal.
self.trigger.emit()
def handle_trigger(self):
# Show that the slot has been called.
print("trigger signal received")
```
--------------------------------
### Initialize QSemaphore in Python
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api/qsemaphore.html
Demonstrates the basic initialization of a QSemaphore object in Python using PyQt. This is a fundamental step before utilizing its synchronization capabilities.
```python
from PyQt5.QtCore import QSemaphore
# Initialize a semaphore with a given count
semaphore = QSemaphore(5)
```
--------------------------------
### Initialize Quick Search Widget
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api/qabstracttransition.html
Initializes the quick search widget on the page. This is a common pattern for interactive documentation sites.
```javascript
$('#searchbox').show(0);
```
--------------------------------
### Initialize Quick Search Widget
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api/qprogressdialog.html
Initializes the quick search widget on the page. This is a common pattern for interactive documentation sites, often implemented using JavaScript.
```javascript
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '5.8.2',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
$('#searchbox').show(0);
```
--------------------------------
### Uninstall PyQt5 GPL Version using pip
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/installation.txt
Uninstalls the GPL version of PyQt5 from your system using pip. This command removes the installed PyQt5 package and its associated files.
```bash
pip3 uninstall pyqt5
```
--------------------------------
### Uninstall PyQt5 Commercial Version using pip
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/installation.txt
Uninstalls the commercial version of PyQt5 from your system using pip. This command removes the installed PyQt5 commercial package and its associated files.
```bash
pip3 uninstall pyqt5-commercial
```
--------------------------------
### Initialize QPointF Object (Python)
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/api/qpointf.html
Demonstrates how to create and initialize a QPointF object in Python. QPointF is used to represent a point in 2D space with floating-point precision. This is a basic usage example.
```python
from PyQt5.QtCore import QPointF
# Create a QPointF object with x=10.5 and y=20.2
point = QPointF(10.5, 20.2)
# Access the coordinates
x_coord = point.x()
y_coord = point.y()
print(f"Point coordinates: ({x_coord}, {y_coord})")
```
--------------------------------
### Run PyQt5 Configuration Script
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/installation.rst.txt
This command executes the configure.py script to set up the PyQt5 build. It assumes the Python interpreter is in the system's PATH. On Windows, a specific path to the Python executable might be required.
```shell
python3 configure.py
```
```shell
c:\Python36\python configure.py
```
--------------------------------
### pyqtlicense No MSVC Runtime Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Omit the 'msvcp140.dll' from the licensed wheel. This is relevant for Windows installations.
```bash
pyqtlicense --no-msvc-runtime
```
--------------------------------
### PyQt5 QDialog - Standard Dialogs Example
Source: https://context7.com/baoboa/pyqt5/llms.txt
This Python code demonstrates how to use various standard dialogs provided by PyQt5, including file selection, color picking, text input, and message boxes. It requires the PyQt5 library to run.
```python
from PyQt5.QtCore import QDir, Qt
from PyQt5.QtWidgets import (
QApplication, QWidget, QPushButton, QLabel,
QVBoxLayout, QFileDialog, QColorDialog,
QFontDialog, QInputDialog, QMessageBox
)
from PyQt5.QtGui import QPalette
class DialogDemo(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Standard Dialogs Demo")
layout = QVBoxLayout()
# File dialog button
file_btn = QPushButton("Open File")
file_btn.clicked.connect(self.open_file_dialog)
self.file_label = QLabel("No file selected")
# Color dialog button
color_btn = QPushButton("Choose Color")
color_btn.clicked.connect(self.open_color_dialog)
self.color_label = QLabel("No color selected")
# Input dialog button
input_btn = QPushButton("Get Input")
input_btn.clicked.connect(self.open_input_dialog)
self.input_label = QLabel("No input")
# Message box button
msg_btn = QPushButton("Show Message")
msg_btn.clicked.connect(self.show_message)
for w in [file_btn, self.file_label, color_btn, self.color_label,
input_btn, self.input_label, msg_btn]:
layout.addWidget(w)
self.setLayout(layout)
def open_file_dialog(self):
filename, _ = QFileDialog.getOpenFileName(
self, "Open File", QDir.homePath(),
"All Files (*);;Python Files (*.py);;Text Files (*.txt)"
)
if filename:
self.file_label.setText(f"Selected: {filename}")
def open_color_dialog(self):
color = QColorDialog.getColor(Qt.blue, self, "Select Color")
if color.isValid():
self.color_label.setText(f"Color: {color.name()}")
self.color_label.setStyleSheet(f"background-color: {color.name()}")
def open_input_dialog(self):
text, ok = QInputDialog.getText(self, "Input Dialog",
"Enter your name:")
if ok and text:
self.input_label.setText(f"Hello, {text}!")
def show_message(self):
reply = QMessageBox.question(
self, "Confirm Action",
"Do you want to proceed?",
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel
)
if reply == QMessageBox.Yes:
QMessageBox.information(self, "Result", "You clicked Yes!")
elif reply == QMessageBox.No:
QMessageBox.warning(self, "Result", "You clicked No!")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
demo = DialogDemo()
demo.show()
sys.exit(app.exec_())
```
--------------------------------
### loadUi
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/designer.rst.txt
Loads a .ui file and returns an instance of the user interface.
```APIDOC
## loadUi
### Description
Load a Qt Designer ``.ui`` file and returns an instance of the user interface.
### Method
`loadUi`
### Parameters
#### Path Parameters
- **uifile** (file name or file-like object) - Required - The file containing the ``.ui`` file.
#### Query Parameters
- **baseinstance** (QWidget) - Optional - The instance of the Qt base class to create the UI in. If not specified, a new instance is created.
- **package** (str) - Optional - The base package for relative imports of custom widgets.
- **resource_suffix** (str) - Optional - Suffix appended to resource file basenames. Defaults to `'_rc'`.
### Request Example
```python
# Example usage (conceptual)
# ui_instance = loadUi('my_ui.ui', baseinstance=self)
```
### Response
#### Success Response (200)
- **QWidget sub-class instance** - The instance of the user interface.
#### Response Example
```python
# Example: An instance of a QWidget subclass implementing the UI.
```
```
--------------------------------
### pyqtlicense Quiet Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Suppresses all progress messages during the wheel generation process.
```bash
pyqtlicense --quiet
```
--------------------------------
### Cooperative Multi-inheritance in PyQt5
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/pyqt4_differences.txt
Demonstrates the recommended way to implement __init__ methods for cooperative multi-inheritance in PyQt5 using super(). This ensures that mixin classes are initialized correctly and avoids issues like double initialization.
```python
class MyQObject(QObject, MyMixin):
def __init__(self, **kwds):
super().__init__(**kwds)
# Other initialisation...
class MyMixin:
def __init__(self, mixin_arg, **kwds):
super().__init__(**kwds)
# Other initialisation...
```
--------------------------------
### Create and Show PyQt5 Widget in Python Shell
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/python_shell.html
Demonstrates creating a QApplication instance, a QWidget, showing it, and then hiding it directly from the Python shell. This showcases PyQt5's event processing while the interpreter waits for input.
```python
from PyQt5.QtWidgets import QApplication, QWidget
a = QApplication([])
w = QWidget()
w.show()
w.hide()
```
--------------------------------
### pyqtlicense No OpenSSL Option
Source: https://github.com/baoboa/pyqt5/blob/master/doc/sphinx/installation.md
Omit the OpenSSL DLLs ('libeay32.dll' and 'ssleay32.dll') from the licensed wheel.
```bash
pyqtlicense --no-openssl
```
--------------------------------
### Initialize PyQt5 QAction with Qt Properties
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/qt_properties.txt
Demonstrates initializing a QAction instance with Qt properties like shortcut, statusTip, and triggered using keyword arguments. This is a convenient way to set initial property values upon object creation.
```python
from PyQt5.QtWidgets import QAction
from PyQt5.QtGui import QKeySequence
# Assuming 'self' is a valid QObject or has a parent context
act = QAction("&Save", self, shortcut=QKeySequence.Save,
statusTip="Save the document to disk", triggered=self.save)
```
--------------------------------
### Example: Signal without Arguments
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/signals_slots.rst.txt
Demonstrates the definition, connection, and emission of a signal that takes no arguments.
```APIDOC
## Example: Signal without Arguments
### Description
This code demonstrates the definition, connection and emit of a signal without arguments.
### Method
`connect_and_emit_trigger()`
`handle_trigger()`
### Endpoint
N/A (This is a class method example)
### Parameters
N/A
### Request Example
```python
from PyQt5.QtCore import QObject, pyqtSignal
class Foo(QObject):
# Define a new signal called 'trigger' that has no arguments.
trigger = pyqtSignal()
def connect_and_emit_trigger(self):
# Connect the trigger signal to a slot.
self.trigger.connect(self.handle_trigger)
# Emit the signal.
self.trigger.emit()
def handle_trigger(self):
# Show that the slot has been called.
print("trigger signal received")
foo_instance = Foo()
foo_instance.connect_and_emit_trigger()
```
### Response
#### Success Response (200)
Prints "trigger signal received" to the console when the signal is emitted and received.
#### Response Example
```
trigger signal received
```
```
--------------------------------
### loadUiType
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/_sources/designer.rst.txt
Loads a .ui file and returns the form class and base class.
```APIDOC
## loadUiType
### Description
Load a Qt Designer ``.ui`` file and return a tuple of the generated *form class* and the *Qt base class*.
### Method
`loadUiType`
### Parameters
#### Path Parameters
- **uifile** (file name or file-like object) - Required - The file containing the ``.ui`` file.
#### Query Parameters
- **from_imports** (bool) - Optional - If set, generates relative import statements for resource modules.
- **resource_suffix** (str) - Optional - Suffix appended to resource file basenames. Defaults to `'_rc'`.
- **import_from** (str) - Optional - The package used for relative import statements. Defaults to `'.'`.
### Request Example
```python
# Example usage (conceptual)
# FormClass, BaseClass = loadUiType('my_ui.ui')
```
### Response
#### Success Response (200)
- **FormClass** (class) - The generated form class.
- **BaseClass** (class) - The Qt base class.
#### Response Example
```python
# Example: (MyFormWidget, QtWidgets.QWidget)
```
```
--------------------------------
### PyQt v3 Style UI Loading
Source: https://github.com/baoboa/pyqt5/blob/master/doc/html/designer.html
This example shows how to use the PyQt v3 style of loading UI files, by subclassing the generated dialog class directly. This approach assumes that the generated ui_imagedialog.py file contains a class named ImageDialog which is already set up to load the UI.
```python
from ui_imagedialog import ImageDialog
class MyImageDialog(ImageDialog):
pass
```