### Complete Q3DBars minimal example in C++ Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtdatavisualization/q3dbars.html A full implementation demonstrating environment setup, graph configuration, and the application execution loop. ```cpp # #include # int main(int argc, char **argv) # { # qputenv("QSG_RHI_BACKEND", "opengl"); # QGuiApplication app(argc, argv); # #! [4] # Q3DBars bars; # bars.setFlags(bars.flags() ^ Qt::FramelessWindowHint); # #! [4] # #! [0] # bars.rowAxis()->setRange(0, 4); # bars.columnAxis()->setRange(0, 4); # #! [0] # #! [1] # QBar3DSeries *series = new QBar3DSeries; # QBarDataRow *data = new QBarDataRow; # *data << 1.0f << 3.0f << 7.5f << 5.0f << 2.2f; # series->dataProxy()->addRow(data); # bars.addSeries(series); # #! [1] # #! [2] # bars.show(); # #! [2] # return app.exec(); # } ``` -------------------------------- ### QMediaPlayer Basic Setup and Playback Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qmediaplayer.html Initialize a QMediaPlayer with audio output, connect position change signals, set media source, configure volume, and start playback. Demonstrates the typical workflow for audio file playback. ```C++ # player = new QMediaPlayer; # audioOutput = new QAudioOutput; # player->setAudioOutput(audioOutput); # connect(player, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64))); # player->setSource(QUrl::fromLocalFile("/Users/me/Music/coolsong.mp3")); # audioOutput->setVolume(50); # player->play(); ``` -------------------------------- ### Complete Q3DSurface Example Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtdatavisualization/q3dsurface.html A full implementation demonstrating the setup, data population, and display of a 3D surface graph. ```cpp # #include # int main(int argc, char **argv) # { # qputenv("QSG_RHI_BACKEND", "opengl"); # QGuiApplication app(argc, argv); # #! [0] # Q3DSurface surface; # surface.setFlags(surface.flags() ^ Qt::FramelessWindowHint); # #! [0] # #! [1] # QSurfaceDataArray *data = new QSurfaceDataArray; # QSurfaceDataRow *dataRow1 = new QSurfaceDataRow; # QSurfaceDataRow *dataRow2 = new QSurfaceDataRow; # #! [1] # #! [2] # *dataRow1 << QVector3D(0.0f, 0.1f, 0.5f) << QVector3D(1.0f, 0.5f, 0.5f); # *dataRow2 << QVector3D(0.0f, 1.8f, 1.0f) << QVector3D(1.0f, 1.2f, 1.0f); # *data << dataRow1 << dataRow2; # #! [2] # #! [3] # QSurface3DSeries *series = new QSurface3DSeries; # series->dataProxy()->resetArray(data); # surface.addSeries(series); # #! [3] # #! [4] # surface.show(); # #! [4] # return app.exec(); # } ``` -------------------------------- ### Audio Output Setup (C++) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qaudiosource.html This snippet sets up an audio output device, configures the audio format, checks for format support, and starts playing audio from a specified source file. ```C++ { sourceFile.setFileName("/tmp/test.raw"); sourceFile.open(QIODevice::ReadOnly); QAudioFormat format; // Set up the format, eg. format.setSampleRate(8000); format.setChannelCount(1); format.setSampleFormat(QAudioFormat::UInt8); QAudioDevice info(QAudioDevice::defaultOutputDevice()); if (!info.isFormatSupported(format)) { qWarning() << "Raw audio format not supported by backend, cannot play audio."; return; } audio = new QAudioSink(format, this); connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); audio->start(&sourceFile); } ``` -------------------------------- ### Set QProcess Environment Variable Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qprocess.html This example shows how to retrieve the system environment, add a new environment variable, and then set it for a QProcess instance before starting it. ```C++ # QProcess process; # QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); # env.insert("TMPDIR", "C:\\MyApp\\temp"); // Add an environment variable # process.setProcessEnvironment(env); # process.start("myapp"); ``` -------------------------------- ### Set up a repetitive QTimer in C++ Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qtimer.html This example demonstrates how to create a QTimer, connect its timeout signal to a slot, and start it to emit signals at regular intervals. ```C++ # QTimer *timer = new QTimer(this); ``` ```C++ # connect(timer, &QTimer::timeout, this, QOverload<>::of(&AnalogClock::update)); ``` ```C++ # timer->start(1000); ``` -------------------------------- ### start() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtspatialaudio/qaudioengine.html Starts the audio engine. ```APIDOC ## start() ### Description Starts the engine. ### Parameters None ### Return Value None ``` -------------------------------- ### Basic Vulkan-Capable QWindow Implementation Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qvulkaninstance.html Complete example showing a QWindow subclass configured for Vulkan rendering with proper initialization in exposeEvent, event handling for continuous rendering, and main application setup. Demonstrates the typical structure for Vulkan-enabled windows including device enumeration and frame rendering. ```C++ # class VulkanWindow : public QWindow # { # public: # VulkanWindow() { # setSurfaceType(VulkanSurface); # } # void exposeEvent(QExposeEvent *) { # if (isExposed()) { # if (!m_initialized) { # m_initialized = true; # // initialize device, swapchain, etc. # QVulkanInstance *inst = vulkanInstance(); # QVulkanFunctions *f = inst->functions(); # uint32_t devCount = 0; # f->vkEnumeratePhysicalDevices(inst->vkInstance(), &devCount, nullptr); # // ... # // build the first frame # render(); # } # } # } # bool event(QEvent *e) { # if (e->type() == QEvent::UpdateRequest) # render(); # return QWindow::event(e); # } # void render() { # // ... # requestUpdate(); // render continuously # } # private: # bool m_initialized = false; # }; # int main(int argc, char **argv) # { # QGuiApplication app(argc, argv); # QVulkanInstance inst; # if (!inst.create()) { # qWarning("Vulkan not available"); # return 1; # } # VulkanWindow window; # window.showMaximized(); # return app.exec(); # } ``` -------------------------------- ### Restart QElapsedTimer and Accumulate Time Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html This example demonstrates using QElapsedTimer::restart() to reset the timer and get the elapsed time since the last start or restart, accumulating time in a loop until a condition is met. ```C++ QElapsedTimer timer; int count = 1; timer.start(); do { count *= 2; slowOperation2(count); } while (timer.restart() < 250); return count; ``` -------------------------------- ### Create a Basic QWizard with Pages (C++) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qwizard.html This example demonstrates how to set up a simple QWizard with an introduction, registration, and conclusion page. It shows the structure for defining wizard pages and integrating them into the main application flow. ```C++ # QWizardPage *createIntroPage() # { # QWizardPage *page = new QWizardPage; # page->setTitle("Introduction"); # QLabel *label = new QLabel("This wizard will help you register your copy " # "of Super Product Two."); # label->setWordWrap(true); # QVBoxLayout *layout = new QVBoxLayout; # layout->addWidget(label); # page->setLayout(layout); # return page; # } # #! [0] # #! [2] # QWizardPage *createRegistrationPage() # { # } # QWizardPage *createConclusionPage() # { # } # int main(int argc, char *argv[]) # #! [9] #! [11] # { # QApplication app(argc, argv); # #ifndef QT_NO_TRANSLATION # QString translatorFileName = QLatin1String("qtbase_"); # translatorFileName += QLocale::system().name(); # QTranslator *translator = new QTranslator(&app); # if (translator->load(translatorFileName, QLibraryInfo::path(QLibraryInfo::TranslationsPath))) # app.installTranslator(translator); # #endif # QWizard wizard; # wizard.addPage(createIntroPage()); # wizard.addPage(createRegistrationPage()); # wizard.addPage(createConclusionPage()); # wizard.setWindowTitle("Trivial Wizard"); # wizard.show(); # return app.exec(); # } ``` -------------------------------- ### Measure elapsed time with QTime Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qdatetime.html Use start() to begin timing and elapsed() to get milliseconds elapsed since start() was called. ```C++ QTime t; t.start(); some_lengthy_task(); qDebug("Time elapsed: %d ms", t.elapsed()); ``` -------------------------------- ### GET program() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qprocess.html Returns the program the process was last started with. ```APIDOC ## GET program() ### Description Returns the program the process was last started with. ### Method GET (Method Call) ### Endpoint program() ### Response #### Success Response (200) - **return** (str) - The program that was last started. ``` -------------------------------- ### Basic QHBoxLayout Usage Example Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qhboxlayout.html A step-by-step example demonstrating how to create a window, add buttons, and arrange them using a horizontal layout. ```cpp # QWidget *window = new QWidget; ``` ```cpp # QPushButton *button1 = new QPushButton("One"); ``` ```cpp # QPushButton *button2 = new QPushButton("Two"); # QPushButton *button3 = new QPushButton("Three"); # QPushButton *button4 = new QPushButton("Four"); # QPushButton *button5 = new QPushButton("Five"); ``` ```cpp # QHBoxLayout *layout = new QHBoxLayout(window); ``` ```cpp # layout->addWidget(button1); # layout->addWidget(button2); # layout->addWidget(button3); # layout->addWidget(button4); # layout->addWidget(button5); ``` ```cpp # window->show(); ``` -------------------------------- ### GET __init__() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html Constructs an invalid QElapsedTimer. A timer becomes valid once it has been started. ```APIDOC ## GET __init__() ### Description Constructs an invalid QElapsedTimer. A timer becomes valid once it has been started. ### Method GET ### Endpoint /__init__() ### Parameters ### Response #### Success Response (200) - No explicit return value (constructor) ``` -------------------------------- ### Initialize camera preview with QMediaCaptureSession Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qcamera.html Set up a camera preview by creating a QMediaCaptureSession, attaching a QCamera, and displaying output on a QVideoWidget. Call preview->show() to display the viewfinder. ```C++ QMediaCaptureSession captureSession; camera = new QCamera; captureSession.setCamera(camera); QVideoWidget *preview = new QVideoWidget; camera->setVideoOutput(preview); preview->show(); ``` -------------------------------- ### GET isValid() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html Returns `false` if the timer has never been started or invalidated by a call to invalidate(). ```APIDOC ## GET isValid() ### Description Returns `false` if the timer has never been started or invalidated by a call to invalidate(). ### Method GET ### Endpoint /isValid() ### Parameters ### Response #### Success Response (200) - bool (bool) - `false` if invalid, `true` otherwise. ``` -------------------------------- ### Basic QQuickView Initialization and Display (C++ Example) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtquick/qquickview.html This C++ example demonstrates the fundamental steps to initialize a QGuiApplication, create a QQuickView, set its QML source, and display it. The code is presented with Python-style comments and is noted as needing porting to Python. ```C++ # //![0] # int main(int argc, char *argv[]) # { # QGuiApplication app(argc, argv); # QQuickView *view = new QQuickView; # view->setSource(QUrl::fromLocalFile("myqmlfile.qml")); # view->show(); # return app.exec(); # } # //![0] ``` -------------------------------- ### QDir - Traverse Directories and Read File Example Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qdir.html Example code showing how to traverse directories and open files using QDir and QFile. Demonstrates changing directories and constructing file paths. ```APIDOC ## Traverse Directories and Read File ### Example Code ```cpp QDir dir = QDir::root(); // "/" if (!dir.cd("tmp")) { // "/tmp" qWarning("Cannot find the \"/tmp\" directory"); } else { QFile file(dir.filePath("ex1.txt")); // "/tmp/ex1.txt" if (!file.open(QIODevice::ReadWrite)) qWarning("Cannot create the file %s", file.name()); } ``` ### Description Demonstrates: 1. Getting the root directory using QDir::root() 2. Changing to a subdirectory using cd() 3. Constructing a file path using filePath() 4. Opening a file with QFile ``` -------------------------------- ### Extracting file suffix Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qfileinfo.html Example of using the suffix() method to get the file extension. ```python # QFileInfo fi("/tmp/archive.tar.gz"); # QString ext = fi.suffix(); // ext = "gz" ``` -------------------------------- ### Find Last Occurrence of Substring in QByteArray Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qbytearray.html Shows how to use `lastIndexOf()` to find the starting index of the last occurrence of a byte sequence, including examples with the `from` parameter to control the search start position. ```C++ QByteArray x("crazy azimuths"); QByteArrayView y("az"); x.lastIndexOf(y); // returns 6 x.lastIndexOf(y, 6); // returns 6 x.lastIndexOf(y, 5); // returns 2 x.lastIndexOf(y, 1); // returns -1 ``` -------------------------------- ### QWaylandApplication.__init__() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qnativeinterface-qwaylandapplication.html Initializes a new instance of the QWaylandApplication class. ```APIDOC ## QWaylandApplication.__init__() ### Description Initializes a new instance of the QWaylandApplication class. ### Signature __init__() ### Parameters None ### Returns None ``` -------------------------------- ### startAngle() - Get Ellipse Segment Start Angle Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qgraphicsellipseitem.html Returns the start angle for an ellipse segment in 16ths of a degree. This angle is used with spanAngle() to represent an ellipse segment or pie. Default value is 0. ```APIDOC ## Method: startAngle() ### Description Returns the start angle for an ellipse segment in 16ths of a degree. This angle is used together with spanAngle() for representing an ellipse segment (a pie). ### Method GET ### Return Type int - The start angle in 16ths of a degree. Default is 0. ### Usage Example ```python item = QGraphicsEllipseItem(0, 0, 100, 100) angle = item.startAngle() print(angle) # Output: 0 ``` ### Related Methods - setStartAngle() - spanAngle() - drawPie() ``` -------------------------------- ### Set up and start audio output in C++ Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qaudiosink.html Configures a raw audio file and initializes a QAudioSink with a specific sample format and rate. ```cpp # void AudioOutputExample::setup() # #! [Audio output setup] # { # sourceFile.setFileName("/tmp/test.raw"); # sourceFile.open(QIODevice::ReadOnly); # QAudioFormat format; # // Set up the format, eg. # format.setSampleRate(8000); # format.setChannelCount(1); # format.setSampleFormat(QAudioFormat::UInt8); # QAudioDevice info(QAudioDevice::defaultOutputDevice()); # if (!info.isFormatSupported(format)) { # qWarning() << "Raw audio format not supported by backend, cannot play audio."; # return; # } # audio = new QAudioSink(format, this); # connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); # audio->start(&sourceFile); # } # #! [Audio output setup] ``` -------------------------------- ### GET processedUSecs() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qaudiosource.html Returns the amount of audio data processed since start() was called, measured in microseconds. ```APIDOC ## Method: processedUSecs() ### Description Returns the amount of audio data processed since start() was called in microseconds. ### Signature ``` processedUSecs() → int ``` ### Return Value - **int** - Amount of audio data processed in microseconds ``` -------------------------------- ### QHelpSearchEngineCore Constructor Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qthelp/qhelpsearchenginecore.html Initializes a new search engine instance with a QHelpEngineCore object. The search engine automatically connects to the help engine's setupFinished signal to begin indexing documentation. ```APIDOC ## Constructor: __init__ ### Description Constructs a new search engine with the given parent. The search engine uses the given helpEngine to access the documentation that needs to be indexed. The QHelpEngineCore's setupFinished() signal is automatically connected to the QHelpSearchEngineCore's indexing function, so that new documentation will be indexed after the signal is emitted. ### Signature ``` __init__(QHelpEngineCore, parent: QObject = None) ``` ### Parameters #### Constructor Parameters - **QHelpEngineCore** (QHelpEngineCore) - Required - The help engine instance used to access documentation - **parent** (QObject) - Optional - The parent object for this search engine (default: None) ``` -------------------------------- ### POST start(DiscoveryMethod) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtbluetooth/qbluetoothdevicediscoveryagent.html Starts Bluetooth device discovery with specific discovery methods to limit the search scope. For example, specifying LowEnergyMethod reduces discovery time by searching only for Bluetooth Low Energy devices. ```APIDOC ## Method: start(DiscoveryMethod) ### Description Starts Bluetooth device discovery with specified discovery methods to limit the search scope. ### Method POST ### Parameters #### Method Parameters - **methods** (DiscoveryMethod) - Required - The discovery methods to use, limiting the scope of the device search. ### Important Notes - The methods parameter determines the type of discovery but does not filter results. For example, classic Bluetooth devices may still appear even if LowEnergyMethod is specified. - This may occur due to previously cached search results being incorporated into the results. - On Windows, cached results for non-advertising devices may be provided. - On iOS, only information about currently advertising devices is provided. - Store the device UUID or Bluetooth address upon first discovery to establish direct connections later without re-discovery. - Using Bluetooth address requires that the remote device's address does not change. ### Related Methods - supportedDiscoveryMethods() - stop() ``` -------------------------------- ### __init__ Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qthelp/qhelpsearchengine.html Constructs a new search engine instance, linking it to a QHelpEngineCore for documentation access and automatically connecting to its setupFinished() signal to initiate indexing. ```APIDOC ## __init__ ### Description Constructs a new search engine instance, linking it to a QHelpEngineCore for documentation access and automatically connecting to its setupFinished() signal to initiate indexing. ### Method Constructor ### Endpoint __init__(QHelpEngineCore, parent: QObject = None) ### Parameters #### Path Parameters - **QHelpEngineCore** (QHelpEngineCore) - Required - The help engine to access the documentation that needs to be indexed. - **parent** (QObject) - Optional - The parent object of the search engine. ``` -------------------------------- ### GET /Attribute.attributes Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qinputmethodevent-attribute.html Access the internal data fields of an Attribute instance including length, start, type, and value. ```APIDOC ## GET /Attribute.attributes ### Description Retrieves the properties stored within an Attribute instance. ### Method GET ### Endpoint Attribute ### Response #### Success Response (200) - **length** (int) - The length of the attribute. - **start** (int) - The starting position of the attribute. - **type** (AttributeType) - The type of attribute. - **value** (Any) - The value of the attribute. ### Response Example { "length": 10, "start": 0, "type": "AttributeType", "value": "example" } ``` -------------------------------- ### Set up QAudioFormat and start audio playback with QIODevice Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qaudiosink.html Configure audio format parameters (sample rate, channel count, sample format), verify format support, create QAudioSink, connect state change signals, and start playback from a QIODevice. Requires QFile, QAudioFormat, QAudioDevice, and QAudioSink. ```C++ sourceFile.setFileName("/tmp/test.raw"); sourceFile.open(QIODevice::ReadOnly); QAudioFormat format; // Set up the format, eg. format.setSampleRate(8000); format.setChannelCount(1); format.setSampleFormat(QAudioFormat::UInt8); QAudioDevice info(QAudioDevice::defaultOutputDevice()); if (!info.isFormatSupported(format)) { qWarning() << "Raw audio format not supported by backend, cannot play audio."; return; } audio = new QAudioSink(format, this); connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); audio->start(&sourceFile); ``` -------------------------------- ### GET msecsTo(QElapsedTimer) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html Returns the number of milliseconds between this QElapsedTimer and _other_. If _other_ was started before this object, the returned value will be negative. If it was started later, the returned value will be positive. The return value is undefined if this object or _other_ were invalidated. ```APIDOC ## GET msecsTo(QElapsedTimer) ### Description Returns the number of milliseconds between this QElapsedTimer and _other_. If _other_ was started before this object, the returned value will be negative. If it was started later, the returned value will be positive. The return value is undefined if this object or _other_ were invalidated. ### Method GET ### Endpoint /msecsTo(QElapsedTimer) ### Parameters #### Request Body - other (QElapsedTimer) - Required - The other QElapsedTimer object to compare with. ### Response #### Success Response (200) - int (int) - The number of milliseconds between timers. ``` -------------------------------- ### POST /QApplication/init Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qapplication.html Initializes the application instance and parses command line arguments. This must be created before any other UI objects. ```APIDOC ## POST /QApplication/init ### Description Initializes the application with the user's desktop settings and parses common command line arguments. There must be precisely one QApplication object. ### Method POST ### Endpoint PyQt6.QtWidgets.QApplication(argv) ### Parameters #### Request Body - **argv** (list) - Required - A list of command line strings (typically sys.argv). ### Request Example { "argv": ["app.py", "-no-gui"] } ### Response #### Success Response (200) - **instance** (QApplication) - The initialized application singleton. #### Response Example { "status": "initialized" } ``` -------------------------------- ### startDragDistance() - Get Start Drag Distance Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qapplication.html Returns the distance in pixels that the mouse must move before a drag operation is initiated. ```APIDOC ## @staticmethod startDragDistance() → int ### Description Returns the distance in pixels that the mouse must move before a drag operation is initiated. ### Method STATIC ### Return Value - **int** - The minimum drag distance in pixels. ### Related Methods - setStartDragDistance() ``` -------------------------------- ### Complete Usage Example Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtnetwork/qnetworkinformation.html A complete example demonstrating how to initialize QNetworkInformation, connect to reachability changes, and handle different reachability states. ```APIDOC ## Complete QNetworkInformation Usage Example ### Description Demonstrates initialization, signal connection, and reachability state handling. ### Code Example ```python from PyQt6.QtCore import QCoreApplication from PyQt6.QtNetwork import QNetworkInformation def onReachabilityChanged(reachability): if reachability == QNetworkInformation.Reachability.Unknown: print("Network reachability is unknown.") elif reachability == QNetworkInformation.Reachability.Disconnected: print("Network is disconnected.") elif reachability == QNetworkInformation.Reachability.Local: print("Network is locally reachable.") elif reachability == QNetworkInformation.Reachability.Site: print("Network can reach the site.") elif reachability == QNetworkInformation.Reachability.Online: print("Network is online.") def main(): app = QCoreApplication([]) # Load default backend if not QNetworkInformation.loadDefaultBackend(): print("QNetworkInformation is not supported on this platform or backend.") return 1 # Get singleton instance netInfo = QNetworkInformation.instance() # Connect to reachability changed signal netInfo.reachabilityChanged.connect(onReachabilityChanged) # Print initial status onReachabilityChanged(netInfo.reachability()) return app.exec() if __name__ == "__main__": main() ``` ### Key Points - Load backend before accessing network information - Get singleton instance after successful load - Connect to reachabilityChanged signal for real-time updates - Handle all reachability states appropriately - Consider platform-specific limitations when interpreting reachability ``` -------------------------------- ### __init__(QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qpalette.html Constructs a palette. You can pass either brushes, pixmaps or plain colors for _windowText_ , _button_ , _light_ , _dark_ , _mid_ , _text_ , _bright_text_ , _base_ and _window_. ```APIDOC ## Method: __init__(QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient) ### Description Constructs a palette. You can pass either brushes, pixmaps or plain colors for _windowText_ , _button_ , _light_ , _dark_ , _mid_ , _text_ , _bright_text_ , _base_ and _window_. ### Signature __init__(QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient, QBrush|QColor|GlobalColor|int|QGradient) ### Parameters - **windowText** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for window text. - **button** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for buttons. - **light** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for light elements. - **dark** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for dark elements. - **mid** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for mid-tone elements. - **text** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for general text. - **bright_text** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for bright text. - **base** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for the base background. - **window** (QBrush|QColor|GlobalColor|int|QGradient) - The color/brush for window backgrounds. ### Returns None ``` -------------------------------- ### GET peerCertificateChain() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtnetwork/qsslconfiguration.html Returns the complete chain of digital certificates from the peer, starting with the immediate certificate and ending with the CA certificate. ```APIDOC ## GET peerCertificateChain()\n\n### Description\nReturns the peer’s chain of digital certificates, starting with the peer’s immediate certificate and ending with the CA’s certificate.\n\n### Method\nGET\n\n### Endpoint\npeerCertificateChain()\n\n### Parameters\nNone\n\n### Request Example\npeerCertificateChain()\n\n### Response\n#### Success Response (200)\n- **chain** (list[QSslCertificate]) - A list of certificates in the peer's chain.\n\n#### Response Example\n{\n "chain": ["QSslCertificate", "QSslCertificate"]\n} ``` -------------------------------- ### GET elapsedUSecs() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qaudiosource.html Returns the microseconds elapsed since start() was called, including time spent in Idle and Suspend states. ```APIDOC ## Method: elapsedUSecs() ### Description Returns the microseconds since start() was called, including time in Idle and Suspend states. ### Signature ``` elapsedUSecs() → int ``` ### Return Value - **int** - Elapsed time in microseconds ``` -------------------------------- ### QWaylandApplication.__init__(QWaylandApplication) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qnativeinterface-qwaylandapplication.html Initializes a new instance of the QWaylandApplication class, potentially as a copy or from another instance. ```APIDOC ## QWaylandApplication.__init__(QWaylandApplication) ### Description Initializes a new instance of the QWaylandApplication class, potentially as a copy or from another instance. ### Signature __init__(QWaylandApplication) ### Parameters - **QWaylandApplication** (QWaylandApplication) - Required - An instance of QWaylandApplication. ### Returns None ``` -------------------------------- ### Audio Input Setup Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qaudiosink.html Sets up audio recording with a specified format and starts recording to a file. Records audio for 3000ms. ```cpp #include #include #include #include #include #include "qaudiodevice.h" #include "qaudiosource.h" #include "qaudiooutput.h" #include "qaudiodecoder.h" #include "qmediaplayer.h" #include "qmediadevices.h" class AudioInputExample : public QObject { Q_OBJECT public: void setup(); public Q_SLOTS: void stopRecording(); void handleStateChanged(QAudio::State newState); private: // Class member QFile destinationFile; // Class member QAudioSource* audio; }; void AudioInputExample::setup() { destinationFile.setFileName("/tmp/test.raw"); destinationFile.open( QIODevice::WriteOnly | QIODevice::Truncate ); QAudioFormat format; // Set up the desired format, for example: format.setSampleRate(8000); format.setChannelCount(1); format.setSampleFormat(QAudioFormat::UInt8); QAudioDevice info = QMediaDevices::defaultAudioInput(); if (!info.isFormatSupported(format)) { qWarning() << "Default format not supported, trying to use the nearest."; } audio = new QAudioSource(format, this); connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); QTimer::singleShot(3000, this, SLOT(stopRecording())); audio->start(&destinationFile); // Records audio for 3000ms } ``` -------------------------------- ### Initialize QTreeView with QFileSystemModel Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qtreeview.html This snippet shows the initial setup for a QTreeView, creating a QFileSystemModel and setting its root path, then instantiating the tree view. ```C++ # QFileSystemModel *model = new QFileSystemModel; # model->setRootPath(QDir::currentPath()); # #! [0] #! [2] #! [4] #! [5] # QTreeView *tree = new QTreeView(splitter); ``` ```C++ # tree->setModel(model); ``` -------------------------------- ### GET restart() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html Restarts the timer and returns the number of milliseconds elapsed since the previous start. This function is equivalent to obtaining the elapsed time with elapsed() and then starting the timer again with start(), but it does so in one single operation, avoiding the need to obtain the clock value twice. Calling this function on a QElapsedTimer that is invalid results in undefined behavior. ```APIDOC ## GET restart() ### Description Restarts the timer and returns the number of milliseconds elapsed since the previous start. This function is equivalent to obtaining the elapsed time with elapsed() and then starting the timer again with start(), but it does so in one single operation, avoiding the need to obtain the clock value twice. Calling this function on a QElapsedTimer that is invalid results in undefined behavior. ### Method GET ### Endpoint /restart() ### Parameters ### Response #### Success Response (200) - int (int) - The number of milliseconds elapsed since the previous start. ``` -------------------------------- ### POST start() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtmultimedia/qaudiosource.html Starts audio input and returns a pointer to the internal QIODevice for reading audio data. The device will already be open and ready for reading. ```APIDOC ## Method: start() ### Description Returns a pointer to the internal QIODevice being used to transfer data from the system's audio input. The device will already be open and read() can read data directly from it. ### Signature ``` start() → QIODevice ``` ### Return Value - **QIODevice** - Pointer to internal QIODevice for reading audio data ### Success Behavior - state() returns QtAudio::IdleState - error() returns QtAudio::NoError - stateChanged signal is emitted ### Error Behavior - If a problem occurs during this process: - error() returns QtAudio::OpenError - state() returns QtAudio::StoppedState - stateChanged signal is emitted ### Notes - The pointer will become invalid after the stream is stopped or if you start another stream - The QIODevice interface can be used to read data directly ### Related Methods - QIODevice interface ``` -------------------------------- ### startDragTime() - Get Start Drag Time Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qapplication.html Returns the time in milliseconds that the mouse button must be held down before a drag operation is initiated. ```APIDOC ## @staticmethod startDragTime() → int ### Description Returns the time in milliseconds that the mouse button must be held down before a drag operation is initiated. ### Method STATIC ### Return Value - **int** - The minimum drag time in milliseconds. ### Related Methods - setStartDragTime() ``` -------------------------------- ### QBackingStore Initialization and Painting Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qbackingstore.html Methods to initialize the backing store and control the start and end of painting operations. ```APIDOC ## CALL __init__(window: QWindow)\n\n### Description\nConstructs an empty surface for the given top-level window.\n\n### Method\nCONSTRUCTOR\n\n### Endpoint\nPyQt6.QtGui.QBackingStore.__init__(window)\n\n### Parameters\n#### Path Parameters\n- **window** (QWindow) - Required - The top-level window for the surface.\n\n## CALL beginPaint(region: QRegion)\n\n### Description\nBegins painting on the backing store surface in the given region. Call this before using paintDevice().\n\n### Method\nMETHOD\n\n### Endpoint\nPyQt6.QtGui.QBackingStore.beginPaint(region)\n\n### Parameters\n#### Path Parameters\n- **region** (QRegion) - Required - The area to begin painting.\n\n## CALL endPaint()\n\n### Description\nEnds painting. Call this after painting with the paintDevice() has ended.\n\n### Method\nMETHOD\n\n### Endpoint\nPyQt6.QtGui.QBackingStore.endPaint() ``` -------------------------------- ### Method: __init__ Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qt3dinput/qlogicaldevice.html Constructs a new QLogicalDevice instance. ```APIDOC ## METHOD __init__ ### Description Constructs a new QLogicalDevice instance with parent _parent_. ### Method Constructor ### Parameters #### Request Body - **parent** (QNode) - Optional - The parent QNode for this logical device. ``` -------------------------------- ### Complete Example - Copy Program Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qcommandlineparser.html A comprehensive example demonstrating how to use QCommandLineParser to create a command-line application with multiple options and positional arguments. ```APIDOC ## Complete Example: Copy Program ### Description This example demonstrates a complete implementation of a command-line copy program using QCommandLineParser with multiple option types and positional arguments. ### Code Example ```cpp int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QCoreApplication::setApplicationName("my-copy-program"); QCoreApplication::setApplicationVersion("1.0"); QCommandLineParser parser; parser.setApplicationDescription("Test helper"); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy.")); parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory.")); // A boolean option with a single name (-p) QCommandLineOption showProgressOption("p", QCoreApplication::translate("main", "Show progress during copy")); parser.addOption(showProgressOption); // A boolean option with multiple names (-f, --force) QCommandLineOption forceOption(QStringList() << "f" << "force", QCoreApplication::translate("main", "Overwrite existing files.")); parser.addOption(forceOption); // An option with a value QCommandLineOption targetDirectoryOption(QStringList() << "t" << "target-directory", QCoreApplication::translate("main", "Copy all source files into ."), QCoreApplication::translate("main", "directory")); parser.addOption(targetDirectoryOption); // Process the actual command line arguments given by the user parser.process(app); const QStringList args = parser.positionalArguments(); // source is args.at(0), destination is args.at(1) bool showProgress = parser.isSet(showProgressOption); bool force = parser.isSet(forceOption); QString targetDir = parser.value(targetDirectoryOption); // ... } ``` ### Usage ``` ./my-copy-program -p source.txt /destination/ ./my-copy-program --force -t /custom/dir source.txt /destination/ ./my-copy-program --help ./my-copy-program --version ``` ``` -------------------------------- ### state() - Get Process State Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qprocess.html Returns the current state of the process. This method allows monitoring whether the process is running, not running, or starting. ```APIDOC ## state() ### Description Returns the current state of the process. ### Method Function ### Return Value - **ProcessState** - The current state of the process ### Related Methods - stateChanged signal - error() ``` -------------------------------- ### Run QML Application with Python Plugin Example Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/qml.html This command demonstrates how to navigate to an example directory and run a QML application (`app.qml`) using `qmlscene`, ensuring the `QML2_IMPORT_PATH` is set correctly for plugin discovery. ```bash cd /path/to/examples/quick/tutorials/extending/chapter6-plugins QML2_IMPORT_PATH=. /path/to/qmlscene app.qml ``` -------------------------------- ### Get capture group offsets Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qregularexpressionmatch.html Use capturedStart() and capturedEnd() to retrieve the start and end positions of a captured group within the subject string. ```C++ QRegularExpression re("abc(\\d+)def"); QRegularExpressionMatch match = re.match("XYZabc123defXYZ"); if (match.hasMatch()) { int startOffset = match.capturedStart(1); // startOffset == 6 int endOffset = match.capturedEnd(1); // endOffset == 9 // ... } ``` -------------------------------- ### Main function demonstrating QElapsedTimer examples Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html This main function initializes a QCoreApplication and calls the various QElapsedTimer example functions to showcase their usage. ```C++ int main(int argc, char **argv) { QCoreApplication app(argc(argc, argv); startExample(); restartExample(); executeSlowOperations(5); executeOperationsForTime(5); } ``` -------------------------------- ### GET elapsed() Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html Returns the number of milliseconds since this QElapsedTimer was last started. Calling this function on a QElapsedTimer that is invalid results in undefined behavior. ```APIDOC ## GET elapsed() ### Description Returns the number of milliseconds since this QElapsedTimer was last started. Calling this function on a QElapsedTimer that is invalid results in undefined behavior. ### Method GET ### Endpoint /elapsed() ### Parameters ### Response #### Success Response (200) - int (int) - The number of milliseconds elapsed. ``` -------------------------------- ### setupData() - Initialize Help Engine Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qthelp/qhelpenginecore.html Sets up the help engine by processing information found in the collection file. Returns true if successful, otherwise false. This function forces immediate initialization of the help engine. ```APIDOC ## setupData() ### Description Sets up the help engine by processing the information found in the collection file and returns true if successful; otherwise returns false. By calling the function, the help engine is forced to initialize itself immediately. Most of the times, this function does not have to be called explicitly because getter functions which depend on a correctly set up help engine do that themselves. ### Method POST ### Return Type bool ### Response Example true ### Notes - qsqlite4.dll needs to be deployed with the application as the help system uses the sqlite driver when loading help collections. ``` -------------------------------- ### QPainter Constructor and Initialization Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qpainter.html Demonstrates two approaches to initializing a QPainter: using the constructor with a paint device parameter, or using the begin() method. The constructor approach is simpler for most cases, while begin() is recommended for external devices like printers where error feedback is needed. ```APIDOC ## QPainter Initialization ### Description Initialize a QPainter for painting operations on a paint device. ### Method 1: Constructor Initialization ```cpp void MyWidget::paintEvent(QPaintEvent *) { QPainter p(this); p.drawLine(drawingCode); // drawing code } ``` ### Method 2: begin() and end() Methods ```cpp void MyWidget::paintEvent(QPaintEvent *) { QPainter p; p.begin(this); p.drawLine(drawingCode); // drawing code p.end(); } ``` ### Usage Notes - Constructor approach: Simpler, automatic cleanup at destruction - begin()/end() approach: Recommended for external devices (printers) where error feedback is needed - Only one painter can paint a device at a time - All painter settings are reset to default values when begin() is called ``` -------------------------------- ### begin(QPaintDevice) Method Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtgui/qpainter.html Begins painting on a specified paint device and returns true if successful. This method resets all painter settings to default values and should be used when error handling is required, particularly for external devices like printers. ```APIDOC ## begin(QPaintDevice) ### Description Begins painting the paint device and returns true if successful; otherwise returns false. ### Method Bool begin(QPaintDevice device) ### Parameters #### Method Parameters - **device** (QPaintDevice) - Required - The paint device to begin painting on ### Return Value - **bool** - Returns true if painting began successfully, false otherwise ### Behavior - All painter settings (setPen(), setBrush(), etc.) are reset to default values when begin() is called - Only one painter can paint a device at a time - Must be followed by a call to end() ### Error Cases The following errors can occur: - Paint device cannot be null (0) - Paint device cannot be a null image (image.isNull() == true) - Only one painter can paint a device at a time - Painting on QImage with format Format_Indexed8 is not supported ### Example ```cpp QPainter painter; if (painter.begin(myDevice)) { // Painting operations painter.end(); } ``` ### Warnings - A paint device can only be painted by one painter at a time - Painting on a QImage with the format Format_Indexed8 is not supported ``` -------------------------------- ### Basic elapsed time measurement with QElapsedTimer Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qelapsedtimer.html Start a timer, perform an operation, and retrieve elapsed milliseconds. This C++ example requires porting to Python. ```C++ QElapsedTimer timer; timer.start(); slowOperation1(); qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds"; ``` -------------------------------- ### QFileInfo.__init__(QFileDevice) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtcore/qfileinfo.html Constructs a new QFileInfo that gives information about the provided QFileDevice. If the file has a relative path, the QFileInfo will also have a relative path. ```APIDOC ## CONSTRUCTOR QFileInfo.__init__(QFileDevice) ### Description Constructs a new QFileInfo that gives information about file _file_. If the _file_ has a relative path, the QFileInfo will also have a relative path. ### Method CONSTRUCTOR ### Endpoint QFileInfo.__init__(file: QFileDevice) ### Parameters #### Path Parameters - No path parameters. #### Query Parameters - No query parameters. #### Request Body - **file** (QFileDevice) - Required - The QFileDevice object to get information about. ### Response #### Success Response (N/A) - Returns a QFileInfo object initialized with information from the given QFileDevice. ``` -------------------------------- ### LicenseWizard Constructor with Page Setup (C++) Source: https://www.riverbankcomputing.com/static/Docs/PyQt6/api/qtwidgets/qwizard.html This constructor for `LicenseWizard` initializes the wizard, setting up multiple pages with unique IDs and defining the starting page. ```cpp LicenseWizard::LicenseWizard(QWidget *parent) : QWizard(parent) { setPage(Page_Intro, new IntroPage); setPage(Page_Evaluate, new EvaluatePage); setPage(Page_Register, new RegisterPage); setPage(Page_Details, new DetailsPage); setPage(Page_Conclusion, new ConclusionPage); setStartId(Page_Intro); ```