Настроить qt creator для python

Разработка приложений на Python в Qt Creator

В прошлом я разработал несколько проектов Qt на C ++ с использованием Qt Creator, но теперь я хочу поэкспериментировать с реализацией Qt на Python. Я обнаружил, что Qt Creator 2.8 и выше поддерживают Python , но я до сих пор не смог понять, как создать приложение Qt на Python с его помощью. Онлайновая документация по этому поводу выглядит скудной.

Как мне создать такой проект в Qt Creator? В идеале я ищу простой проект «Hello World», который я могу открыть в Qt Creator и использовать его в качестве отправной точки для создания чего-либо.

2 ответа

В настоящее время Qt Creator позволяет создавать файлы Python (не проекты) и запускать их. Он также имеет подсветку синтаксиса, но в нем отсутствуют более сложные функции, такие как автозаполнение.

Для запуска сценариев требуется некоторая настройка (я использовал этот руководство). Откройте Qt Creator и перейдите в Tools->Options->Environment->External Tools . Нажмите Add->Add category и создайте новую категорию (например, Python ). Затем выберите созданную категорию и нажмите Add->Add Tool , чтобы создать новый инструмент — RunPy например. Выберите созданный инструмент и заполните поля справа:

  1. Описание — любое значение
  2. Исполняемый файл — путь к python.exe
  3. Аргументы — %
  4. Рабочий каталог — %
  5. Среда — QT_LOGGING_TO_CONSOLE=1

Вы получаете что-то вроде этого:

Теперь перейдите в File->New File or Project->Python и выберите Python source file

Вы также можете добавить к нему pyuic: Снова нажмите кнопку Add->Add Tool , чтобы создать новый инструмент — PyUic сейчас. Выберите его еще раз и заполните поля справа:

  1. Описание — любое значение
  2. Исполняемый файл — путь к pyuic5
  3. Аргументы — -o UI%.py -x %
  4. Рабочий каталог — %
  5. Среда — QT_LOGGING_TO_CONSOLE=1

Тогда у вас должен быть подключен и PyUic.

Спасибо за это, это очень помогло.

Я настроил раздел сборки и запуска нового набора для python, используя ваши инструкции, которые, кажется, работают довольно хорошо.

Вот настройки сборки:

Вот настройки запуска:

обратите внимание, что я имею /usr /bin /python в качестве ссылки на /usr/bin/python3.6

Вот настройки файла проекта:

Единственное, что нужно, это войти в инструменты -> параметры -> создать и запустить и отменить выбор «всегда создавать проект перед его развертыванием» и «всегда развертывать проект перед его выполнением».

После того как вы спроектировали форму, вы можете нажать кнопку build, чтобы создать файл UI.py и запустить текущий выбранный исходный файл python, нажав кнопку run.

Для новичков PyQt, таких как я, я обнаружил, что следующий ресурс особенно полезен при запуске . (хотя я использую Linux, а не Windows) .

Я также добавил pdb — отладчик Python

который затем можно выбрать, нажав кнопку над кнопкой запуска:

, прежде чем нажать кнопку «Выполнить». Вы можете установить точки останова в своем коде с помощью следующего фрагмента, где я добавил DEBUG = 1 в системную среду в настройках run запуска pdb и DEBUG = 0 в env python выполнения:

Источник

Qt for Python Quick startВ¶

RequirementsВ¶

Before you can install Qt for Python, first you must install the following software:

We recommend using a virtual environment, such as venv or virtualenv

InstallationВ¶

Creating and activating an environment You can do this by running the following on a terminal:

python -m venv env, (Your Python executable might be called python3 )

source env/bin/activate for Linux and macOS

env\Scripts\activate.bat for Windows

Installation

Now you are ready to install the Qt for Python packages using pip . From the terminal, run the following command:

pip install pyside6, for the latest version.

pip install pyside6==6.0, for the version 6.0 specifically.

It is also possible to install a specific snapshot from our servers. To do so, you can use the following command:

Test your installation

Now that you have Qt for Python installed, test your setup by running the following Python constructs to print version information:

Create a Simple ApplicationВ¶

Your Qt for Python setup is ready. You can explore it further by developing a simple application that prints “Hello World” in several languages. The following instructions will guide you through the development process:

Imports

Create a new file named hello_world.py , and add the following imports to it.:

The PySide6 Python module provides access to the Qt APIs as its submodule. In this case, you are importing the QtCore , QtWidgets , and QtGui submodules.

Main Class

Define a class named MyWidget , which extends QWidget and includes a QPushButton and QLabel.:

The MyWidget class has the magic member function that randomly chooses an item from the hello list. When you click the button, the magic function is called.

Application execution

Now, add a main function where you instantiate MyWidget and show it.:

Run your example by writing the following command: python hello_world.py.

Try clicking the button at the bottom to see which greeting you get.

В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

Qt for Python Getting StartedВ¶

This page is focused on building Qt for Python from source. If you just want to install PySide6, you need to run: pip install pyside6.

For more details, refer to our Quick Start guide. Additionally, you can check the FAQ related to the project.

General RequirementsВ¶

The following prerequisites must be installed before you build Qt for Python. On Linux you might get them with your operating system package manager, on macOS you might get them with brew , and on Windows you can download the installer from each website.

libclang: The libclang library, recommended: version 10 for 6.0+. Prebuilt versions for each OS can be downloaded here.

Guides per platformВ¶

You can refer to the following pages for platform specific instructions:

Windows

macOS

Linux

The Qt for Python does not yet support WebAssembly and the mobile operating

systems (Android or iOS).

Most Linux-based embedded OS provide PySide with their official package manager (for example, Raspbian and ArchlinuxARM).

A normal building command will look like this:

Which will build and install the project with debug symbols, including the tests, using ninja (instead of make), and considering only the module subset of QtCore , QtGui , and QtWidgets

Other important options to consider are:

—cmake , to specify the path to the cmake binary,

—reuse-build , to rebuild only the modified files,

—openssl=/path/to/openssl/bin , to use a different path for OpenSSL,

—standalone , to copy over the Qt libraries into the final package to make it work on other machines,

—doc-build-online , to build documentation using the online template.

Testing the installationВ¶

Once the installation finishes, you will be able to execute any of our examples:

Running TestsВ¶

Using the —build-tests option will enable us to run all the auto tests inside the project:

On Windows, don’t forget to have qmake in your path ( set PATH=E:\Path\to\Qt\6.0.0\msvc2019_64\bin;%PATH%)

You can also run a specific test (for example qpainter_test ) by running:

Building the documentationВ¶

Starting from 5.15, there are two options to build the documentation:

1. Building rst-only documentation (no API)В¶

The process of parsing Qt headers to generate the PySide API documentation can take several minutes, this means that modifying a specific section of the rst files we currently have, might become a hard task.

For this, you can install sphinx on a virtual environment, and execute the following command:

which will generate a html/ directory with the following structure:

so you can open the main page html/pyside6/index.html on your browser to check the generated files.

This is useful when updating the general sections of the documentation, adding tutorials, modifying the build instructions, and more.

2. Building the documentation (rst + API)В¶

The documentation is being generated using qdoc to get the API information, and also sphinx for the local Python related notes.

The system required libxml2 and libxslt , also on the Python environment, sphinx and graphviz need to be installed before running the installation process:

After installing graphviz , the dot command needs to be in PATH, otherwise, the process will fail. Installing graphviz system-wide is also an option.

Since the process rely on a Qt installation, you need to specify where the qtbase directory you will use with your qmake is located:

Once the build process finishes, you can go to the generated *_build/*_release/pyside6 directory, and run:

The apidoc make target builds offline documentation in QCH (Qt Creator Help) format by default. You can switch to building for the online use with the —doc-build-online configure option.

The target executes several steps:

The qdoc tool is run over the Qt source code to produce documentation in WebXML format.

shiboken6 is run to extract the functions for which bindings exist from WebXML and convert it into RST.

sphinx is run to produce the documentation in HTML format.

Re-running the command will not execute step 1 unless the file qdoc_output/webxml/qtcore-index.webxml is removed from the build tree. Similarly, step 2 will not be executed unless the file rst/PySide6/QtCore/index.rst is removed.

Finally, you will get a html directory containing all the generated documentation. The offline help files, PySide.qch and Shiboken.qch , can be moved to any directory of your choice. You can find Shiboken.qch in the build directory, *_build\*_release\shiboken6\doc\html .

If you want to temporarily change a .rst file to examine the impact on formatting, you can re-run sphinx in the doc directory:

Viewing offline documentationВ¶

The offline documentation (QCH) can be viewed using the Qt Creator IDE or Qt Assistant, which is a standalone application for viewing QCH files.

To view the QCH using Qt Creator, following the instructions outlined in Using Qt Creator Help Mode. If you chose to use Qt Assistant instead, use the following command to register the QCH file before launching Qt Assistant:

Qt Assistant renders the QCH content using the QTextBrowser backend, which supports a subset of the CSS styles, However, Qt Creator offers an alternative litehtml-based backend, which offers better browsing experience. At the moment, this is not the default backend, so you have to select the litehtml backend explicitly under the General tab in Qt Creator >> Tools >> Options >> Help .

Using the internal toolsВ¶

A set of tools can be found under the tools/ directory inside the pyside-setup repository.

checklibs.py : Script to analyze dynamic library dependencies of Mach-O binaries. To use this utility, just run:

This script was fetched from this repository.

create_changelog.py : Script used to create the CHANGELOG that you can find in the dist/ directory. Usage:

debug_windows.py : This script can be used to find out why PySide modules fail to load with various DLL errors like Missing DLL or Missing symbol in DLL.

You can think of it as a Windows version of ldd / LD_DEBUG .

Underneath, it uses the cdb.exe command line debugger and the gflags.exe tool, which are installed with the latest Windows Kit.

The aim is to help developers debug issues that they may encounter using the PySide imports on Windows. The user should then provide the generated log file.

Incidentally it can also be used for any Windows executables, not just Python. To use it just run:

missing_bindings.py : This script is used to compare the state of PySide and PyQt regarding available modules and classses. This content is displayed in our wiki page, and can be used as follows:

The script relies on BeautifulSoup to parse the content and generate a list of the missing bindings.

В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

First steps with Qt Designer
Use Qt Designer’s drag and drop interface to design your GUI

Creating applications with Qt Designer course

This tutorial requires Qt Creator to be installed — you can download it free from the Qt website. Go to https://www.qt.io/download and download the Qt package. You can opt to install only Creator during the installation.

Open up Qt Creator and you will be presented with the main window. The designer is available via the tab on the left hand side. However, to activate this you first need to start creating a .ui file.

The Qt Creator interface, with the Design section shown on the left.

To create a .ui file go to File -> New File or Project. In the window that appears select Qt under Files and Classes on the left, then select Qt Designer Form on the right. You’ll notice the icon has «ui» on it, showing the type of file you’re creating.

Create a new Qt .ui file.

In the next step you’ll be asked what type of widget you want to create. If you are starting an application then Main Window is the right choice. However, you can also create .ui files for dialog boxes, forms and custom compound widgets.

Select the type of widget to create, for most applications this will be Main Window.

Next choose a filename and save folder for your file. Save your .ui file with the same name as the class you’ll be creating, just to make make subsequent commands simpler.

Choose save name and folder your your file.

Finally, you can choose to add the file to your version control system if you’re using one. Feel free to skip this step — it doesn’t affect your UI.

Optionally add the file to your version control, e.g. Git.

Laying out your Main Window

You’ll be presented with your newly created main window in the UI designer. There isn’t much to see to begin with, just a grey working area representing the window, together with the beginnings of a window menu bar.

The initial view of the created main window.

You can resize the window by clicking the window and dragging the blue handles on each corner.

The initial view of the created main window.

The first step in building an application is to add some widgets to your window. In our first applications we learnt that to set the central widget for a QMainWindow we need to use .setCentralWidget() . We also saw that to add multiple widgets with a layout, we need an intermediary QWidget to apply the layout to, rather than adding the layout to the window directly.

Qt Creator takes care of this for you automatically, although it’s not particularly obvious about it.

To add multiple widgets to the main window with a layout, first drag your widgets onto the QMainWindow . Here we’re dragging 3 labels. It doesn’t matter where you drop them.

Main window with 1 labels and 1 button added.

We’ve created 2 widgets by dragging them onto the window, made them children of that window. We can now apply a layout.

Find the QMainWindow in the right hand panel (it should be right at the top). Underneath you see centralwidget representing the window’s central widget. The icon for the central widget show the current layout applied. Initially it has a red circle-cross through it, showing that there is no layout active.

Right click on the QMainWindow object, and find ‘Layout’ in the resulting dropdown.

Right click on the main window, and choose layout.

Next you’ll see a list of layouts which you can apply to the window. Select Lay Out Horizontally and the layout will be applied to the widget.

Select layout to apply to the main window.

The selected layout is applied to the the centralwidget of the QMainWindow and the widgets are added the layout, being laid out depending on the selected layout. Note that in Qt Creator you can actually drag and re-order the widgets within the layout, or select a different layout, as you like. This makes it especially nice to prototyping and trying out things.

Vertical layout applied to widgets on the main window.

Using your generated .ui file

We’ve created a very simple UI. The next step is to get this into Python and use it to construct a working application.

First save your .ui file — by default it will save at the location you chosen while creating it, although you can choose another location if you like.

The .ui file is in XML format. To use our UI from Python we have two alternative methods available —

  1. load into into a class using the .loadUI() method
  2. convert it to Python using the pyuic5 tool.

These two approaches are covered below. Personally I prefer to convert the UI to a Python file to keep things similar from a programming & packaging point of view.

Loading the .ui file directly

To load .ui files we can use the uic module included with PyQt5, specifically the uic.loadUI() method. This takes the filename of a UI file and loads it creating a fully-functional PyQt5 object.

For PySide2 you can use a QUiLoader instance and call the loader.load() method to accomplish the same thing.

A (very) simple UI designed in Qt Creator

As the uid.loadUI() method turns an instance object you cannot attach custom __init__() code. You can however handle this through a custom setup function

To load a UI from the __init__ block of an existing widget (e.g. a QMainWindow ) you can use uic.loadUI(filename, self) for PyQt5.

The PySide2 loader does not support this approach — the second parameter is for the parent widget of the widget you’re creating. This prevents you adding custom code to the initialization of the widget, but you can work around this with a separate init function.

Converting your .ui file to Python

To generate a Python output file run pyuic5 from the command line, passing the .ui file and the target file for output, with a -o parameter. The following will generate a Python file named MainWindow.py which contains our created UI.

If you’re using PyQt4 the tool is named `pyuic4`, but is otherwise completely identical.

You can open the resulting MainWindow.py file in an editor to take a look, although you should not edit this file. The power of using Qt Creator is being able to edit, tweak and update your application while you develop. Any changes made to this file will be lost when you update it. However, you can override and tweak anything you like when you import and use the file in your applications.

Importing the resulting Python file works as for any other. You can import your class as follows. The pyuic5 tool appends Ui_ to the name of the object defined in Qt Creator, and it is this object you want to import.

To create the main window in your application, create a class as normal but subclassing from both QMainWindow and your imported Ui_MainWindow class. Finally, call self.setupUi(self) from within the __init__ to trigger the setup of the interface.

This produces exactly the same result as before.

A (very) simple UI designed in Qt Creator

That’s it. Your window is now fully set up. Since the use of a .ui file abstracts out the UI-specific code, you can use this same pattern to load any interface you design.

Create GUI Applications with Python & Qt5
The easy way to create desktop applications

The complete guide to building GUI applications with PyQt5. From the basics of creating a desktop window to the key features you need to build real apps.

Downloadable ebook (PDF, ePub) & Complete Source code

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount on all books and courses.

[[ activeDiscount.description ]] I’m giving a [[ activeDiscount.discount ]]% discount on all books and courses.

Adding application logic

You can interact with widgets created through Qt Creator just as you would those created with code. To make things simpler uic adds all child widgets to the window object by their id name as specified in Qt Creator. We’ll cover how to work with these in the next part.

Источник

Читайте также:  Как починить бардачок ваз 2110
Оцените статью