Как установить pyqt5 на windows 10

PyQt-How-to-install-pyQt5-on-Windows-10

How to install pyQt5 on Windows 10
How to install pyQt5 on Windows 10

Step1:

Download and install latest python exe from https://www.python.org/downloads/

Step2:

Update pip version if any update available using below command

python -m pip install —upgrade pip

Example:
C:\Users<username>\AppData\Local\Programs\Python\Python38-32\Scripts>python -m pip install —upgrade pip

Step3:

Install PyQt5 using below command — recommended methoed
C:\Users<username>\AppData\Local\Programs\Python\Python38-32\Scripts>pip.exe install pyQt5

(or)

Download pyQt5 whl(wheel) file from https://pypi.org/project/PyQt5
Install whl(wheel) file using below command

C:\Users<username>\AppData\Local\Programs\Python\Python38-32\Scripts>pip.exe install D:\Softwares\PyQt5-5.14.1-5.14.0-cp35.cp36.cp37.cp38-none-win_amd64.whl

Python (programming language):(https://en.wikipedia.org/wiki/Python_(programming_language))

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991,
Python’s design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and
object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.

Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including procedural, object-oriented,
and functional programming. Python is often described as a «batteries included» language due to its comprehensive standard library.

Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0, released in 2000, introduced features like list
comprehensions and a garbage collection system capable of collecting reference cycles. Python 3.0, released in 2008, was a major revision of the language that is not completely backward-compatible, and much Python 2 code does not run unmodified on Python 3.

The Python 2 language, i.e. Python 2.7.x, was officially discontinued on January 1, 2020 (first planned for 2015) after which security
patches and other improvements will not be released for it. With Python 2’s end-of-life, only Python 3.5.x[32] and later are supported.

Python interpreters are available for many operating systems. A global community of programmers develops and maintains CPython, an open
source reference implementation. A non-profit organization, the Python Software Foundation, manages and directs resources for Python and CPython development

pip (package manager):

pip is a de facto standard package-management system used to install and manage software packages written in Python. Many packages
can be found in the default source for packages and their dependencies — Python Package Index (PyPI).

Most distributions of Python come with pip preinstalled. Python 2.7.9 and later (on the python2 series), and Python 3.4 and later
include pip (pip3 for Python 3) by default.

pip is a recursive acronym for «Pip Installs Packages».

Command-line interface

An output of pip install virtualenv
One major advantage of pip is the ease of its command-line interface, which makes installing Python software packages as easy as issuing
a command:

pip install some-package-name

Users can also easily remove the package:

pip uninstall some-package-name

Most importantly pip has a feature to manage full lists of packages and corresponding version numbers, possible through a «requirements» file.[5] This permits the efficient re-creation of an entire group of packages in a separate environment (e.g. another computer) or virtual environment. This can be achieved with a properly formatted file and the following command[8], where requirements.txt is the name of the file:

pip install -r requirements.txt

Install some package for a specific version python, where ${version} is replaced for 2, 3, 3.4, etc.:

pip${version} install some-package-name

pip list -> it will display install packages
pip show -> it will inoformation about installed packages like installation path

PyQt:(https://en.wikipedia.org/wiki/PyQt)

PyQt is a Python binding of the cross-platform GUI toolkit Qt, implemented as a Python plug-in. PyQt is free software developed by the
British firm Riverbank Computing. It is available under similar terms to Qt versions older than 4.5; this means a variety of licenses
including GNU General Public License (GPL) and commercial license, but not the GNU Lesser General Public License (LGPL).
PyQt supports Microsoft Windows as well as various flavours of UNIX, including Linux and MacOS (or Darwin).

PyQt implements around 440 classes and over 6,000 functions and methods including:

a substantial set of GUI widgets
classes for accessing SQL databases (ODBC, MySQL, PostgreSQL, Oracle, SQLite)
QScintilla, Scintilla-based rich text editor widget
data aware widgets that are automatically populated from a database
an XML parser
SVG support
classes for embedding ActiveX controls on Windows (only in commercial version)
To automatically generate these bindings, Phil Thompson developed the tool SIP, which is also used in other projects.

In August 2009, Nokia, the then owners of the Qt toolkit, released PySide, providing similar functionality, but under the LGPL,
after failing to reach an agreement with Riverbank Computing to change its licensing terms to include LGPL as an alternative license.

What is SIP?

One of the features of Python that makes it so powerful is the ability to take existing libraries, written in C or C++, and make them available as Python extension modules. Such extension modules are often called bindings for the library.

SIP is a collection of tools that makes it very easy to create Python bindings for C and C++ libraries. It was originally developed in 1998 to create PyQt, the Python bindings for the Qt toolkit, but can be used to create bindings for any C or C++ library. For example it is also used to generate wxPython, the Python bindings for wxWidgets.

SIP comprises a set of build tools and a sip module. The build tools process a set of specification files and generates C or C++ code which is then compiled to create the bindings extension module. Several extension modules may be installed in the same Python package. Extension modules can be built so that they are are independent of the version of Python being used. In other words a wheel created from them can be installed with any version of Python starting with v3.5.

The specification files contain a description of the interface of the C or C++ library, i.e. the classes, methods, functions and variables. The format of a specification file is almost identical to a C or C++ header file, so much so that the easiest way of creating a specification file is to edit a copy of the corresponding header file.

The sip module provides support functions to the automatically generated code. The sip module is installed as part of the same Python package as the generated extension modules. Unlike the extension modules the sip module is specific to a particular version of Python (e.g. v3.5, v3.6, v3.7, v3.8).

SIP makes it easy to exploit existing C or C++ libraries in a productive interpretive programming environment. SIP also makes it easy to take a Python application (maybe a prototype) and selectively implement parts of the application (maybe for performance reasons) in C or C++.

Время на прочтение
3 мин

Количество просмотров 52K

Привет, Хабр! Сегодня я вас хочу научить делать интерфейс на Python 3&PyQt5.

Установка PyQt5

Для того, чтобы установить PyQt5 в Windows или MacOS, откройте Командную строку или Терминал и введите:

pip3 install PyQt5

Для Linux, откройте Терминал и введите:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python3-pyqt5

Hello, World!

А сейчас сделаем Hello World приложение. Создайте файл Python, откройте его и введите такой код:

from PyQt5.QtWidgets import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('Hello, world!!!', self)
        self.lbl.move(30, 30)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Когда вы запустите, должна получится примерно такая картина:

Окно Hello, world на Ubuntu

Окно Hello, world на Ubuntu

Меняем шрифт надписи

А теперь поменяем шрифт надписи. Теперь код станет таким:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('Hello, world!!!', self)
        self.lbl.move(30, 30)
        self.font = QFont() # создаём объект шрифта
        self.font.setFamily("Rubik") # название шрифта
        self.font.setPointSize(12) # размер шрифта
        self.font.setUnderline(True) # подчёркивание
        self.lbl.setFont(self.font) # задаём шрифт метке


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Пример рассчитан на то, что у вас уже установлен шрифт Rubik от Google Fonts. Если нет, его всегда можно скачать отсюда.

Более продвинутая разметка с XHTML

А теперь добавим XHTML. Например, так:

from PyQt5.QtWidgets import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('<i>Hello</i>, <b>world</b>!!! <s><b>123</b></s>', self)
        self.lbl.move(30, 30)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Те, кто хотя бы немного знают XHTML, заметят, что надпись Hello сделана курсивом, слово world — жирным, а 123 — и вычеркнуто, и жирное.

Шпаргалка по XHTML

<b>123</b>

Жирный текст

<i>123</i>

Курив

<u>123</u>

Подчёркивание

<s>123</s>

Вычёркивание

<code>123</code>

Код (моноширным шрифтом)

<sup>123</sup>

Надстрочный текст

<sub>123</sub>

Подстрочный текст

<span style=»font-size:16pt;»>123</span>

Размер текста 16 пунктов

<span style=»color:#cc0000;»>123</span>

Красный текст

<span style=» background-color:#00ff00;»>123</span>

Текст на ярко-зелёном фоне.

<span align=»center»>123</span>

Выравнивание по центру

Кстати, я знаю такой конструктор HTML. Лично мне он по душе. Только сложно вставлять свои тэги.

Больше надписей!

А теперь сделаем 2 надписи:

from PyQt5.QtWidgets import *
import sys


class MainWindow(QMainWindow): # главное окно
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()
    def setupUi(self):
        self.setWindowTitle("Hello, world") # заголовок окна
        self.move(300, 300) # положение окна
        self.resize(200, 200) # размер окна
        self.lbl = QLabel('<i>Hello</i>, <b>world</b>!!!', self)
        self.lbl.move(30, 30)
        self.lbl2 = QLabel('<u>Ещё одна метка</u>', self)
        self.lbl2.move(50, 50)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

На вторую я тоже добавил форматирование (подчёркивание), а у первой убрал 123.

Окно без resize()

Все предыдущие примеры использовали такую конструкцию:

self.resize(200, 200)

Но без этой конструкции можно обойтись, так как виджеты будут сами себе расчищать место.

Подсказки

Ко всем виджетам можно добавить подсказку. Например (привожу только важную для понимания часть кода):

self.lbl.setToolTip('This is a <b>QLabel</b>')

Эпилог

Вот и всё. В следующей части я постараюсь описать кнопки, меню и события.

До новых встреч!

In this article, we will be looking at the stepwise procedure to install the PyQt for python in Windows. PyQt is a Python binding of the cross-platform GUI toolkit Qt, implemented as a Python plug-in. PyQt is free software developed by the British firm Riverbank Computing. 

Features of PyQt:

There are more than six hundred classes covering a range of features such as:

  • Graphical User Interfaces
  • SQL Databases
  • Web toolkits
  • XML processing
  • Networking

Installing PyQt for Python on Windows:

Follow the below steps to install PyQt for python on Windows:

Step 1:Verify if python is installed on your system.

Here, the user can simply run the below command in the command prompt or the power shell of the windows to verify if the python is already installed in the system or not. If python is already installed in the system the output of the command will be the running version of python and if not installed it will produce an error. In case if python is not installed the user can refer to How to Install Python.

Command to check if python is already installed:

python --version

Output:

Check python version

Step 2:Verify that PyQt is not installed before:

In this, the user has to simply type the below command to verify if the PyQt is not installed before, if installed the user has no need to follow the below steps mentioned.

Command:

pip list

Output:

list all packages installed

Step 3:Install the PyQt:

Here, it is the final step to install the PyQt in python just the user needs to type the below-mentioned article, the PyQt5 will be successfully installed in the system, and further by repeating step-2 the user can verify if the PyQt is installed.

Command:

 pip install PyQt5

Output:

installing pyqt on windows

At this point, you have successfully installed PyQt for python on Windows.

Last Updated :
17 Dec, 2021

Like Article

Save Article

Установка PyQt5 на Windows 10

PyQt – это свободная библиотека для создания графических интерфейсов на языке Python. Она позволяет создавать кроссплатформенные программы, используя стандартные средства языка Python. PyQt5 является последней версией PyQt и работает на многих платформах, в том числе на Windows 10.

В этой статье мы рассмотрим, как установить PyQt5 на Windows 10. Начнем со скачивания и установки Python.

1. Установка Python

Для начала нам нужно установить Python. На момент написания этой статьи последняя версия Python – 3.9.4. Вы можете скачать ее с официального сайта python.org.

Установка Python на Windows очень проста. Просто запустите установочный файл и следуйте инструкциям по установке. После установки проверьте, что Python установлен корректно, введя в командной строке команду «python —version».

2. Установка PyQt5

После того, как Python установлен, можно перейти к установке PyQt5. PyQt5 можно установить с помощью пакетного менеджера pip, который уже включен в установку Python.

Для установки PyQt5 с помощью pip выполните следующую команду в командной строке:

pip install pyqt5

Эта команда загрузит и установит последнюю версию PyQt5.

3. Проверка установки

После установки PyQt5 можно проверить, что все работает корректно, создав простой GUI-пример.

Создайте новый файл с именем «example.py» и добавьте следующий код:

import sys
from PyQt5.QtWidgets import QApplication, QWidget

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    window.setWindowTitle('PyQt5 Example')
    window.setGeometry(100, 100, 400, 300)
    window.show()
    sys.exit(app.exec_())

Этот код создает новое приложение, создает главное окно и отображает его. Запустите этот код, чтобы убедиться, что установка прошла успешно. Вы должны увидеть пустое окно с заголовком «PyQt5 Example».

4. Установка Qt Designer

Установка PyQt5 включает в себя Qt Designer – инструмент для создания графических интерфейсов. Qt Designer позволяет создавать пользовательские виджеты и размещать их на форме. С помощью Qt Designer вы можете определить внешний вид приложения без написания одной строки кода.

Qt Designer включен в инсталлятор PyQt5, но его можно также установить вручную. Qt Designer можно найти на сайте qt.io. Скачайте и установите пакет Qt Designer для вашей версии Windows.

5. Создание графического интерфейса с помощью Qt Designer

Qt Designer – это интуитивно понятный инструмент для создания графических интерфейсов. Он позволяет создавать пользовательские виджеты и размещать их на форме. С помощью Qt Designer вы можете определить внешний вид приложения без написания одной строки кода.

Чтобы создать форму с помощью Qt Designer, выполните следующие шаги:

1. Запустите Qt Designer.
2. Выберите File -> New. Выберите шаблон формы «Main Window».
3. Добавьте виджеты, которые вы хотите использовать, к форме.
4. Установите свойства объектов.
5. Сохраните файл формы.

После создания формы в Qt Designer сохраните ее в XML-файле. Этот файл можно загрузить в Python-код с помощью метода «loadUi» из модуля PyQt5.uic.

6. Создание окна на Python с помощью Qt Designer

Чтобы загрузить файл формы, созданной в Qt Designer, в Python окно, добавьте следующий код в свой Python-файл:

from PyQt5 import QtCore, QtGui, QtWidgets, uic

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        uic.loadUi('myform.ui', self)
        self.show()

app = QtWidgets.QApplication([])
application = MyWindow()
application.show()
app.exec_()

В этом коде мы создаем класс «MyWindow», который наследует от класса «QMainWindow» из PyQt5. Мы загружаем файл формы, созданный в Qt Designer, с помощью метода «loadUi» из модуля PyQt5.uic и показываем главное окно с помощью метода «show()».

7. Заключение

В этой статье мы рассмотрели, как установить PyQt5 на Windows 10 и создать графический интерфейс с помощью Qt Designer. PyQt5 является мощной библиотекой для создания кроссплатформенных приложений на языке Python. Она обладает широким спектром функций и возможностей для создания графических интерфейсов.

PyQt is often not installed by default. The PyQt module can be used to create desktop applications with Python. In this article you’ll learn how to install the PyQt module.

Desktop applications made with PyQt are cross platform, they will work on Microsoft Windows, Apple Mac OS X and Linux computers (including Raspberry Pi).

Related Course: Create GUI Apps with Python PyQt5

How to install PyQt5 on Windows?

To install PyQt on Windows there are a few steps you need to take.
First use the installer from the qt-project website, from qt to install PyQt.

Next you want to install a Python version 3.3 or newer. Check the box to add all of the PyQt5 extras. It’s not necessary to compile everything from source, you can install all the required packages with the installer.

On Python >= 3.6, you can also try this command:

1
pip install pyqt5

It should work without problems.

How to install PyQt5 on Mac OS X?

On Apple Mac OS X installation is a bit simpler. The first step to take is to install the Mac OS X binary. This installs the PyQt GUI library.

But to use it from Python, you also need Python module. This is where the tool brew comes in.
You can use brew to install pyqt (in the terminal):

1
brew install pyqt

How to install PyQt5 on Linux?

Python is often installed by default on Linux (in nearly all of the distributions including Ubuntu). But you want to make sure to use Python 3, because of all the features and ease of use. You can verify that you have the newest Python version with the command:

1
python --version

On Ubuntu Linux they sometimes include two versions of python, python3 and python. In that case use Python 3.

Once you have Python ready, the next step is to install PyQt.

This isn’t hard to do if you have some Linux experience. You can install PyQt your software package manager. Which package manager to use depends on which Linux distribution you are using.

On Ubuntu Linux / Debian Linux you can use the command:

1
sudo apt-get install python3-pyqt5

For CentOS 7 use the command:

1
yum install qt5-qtbase-devel

For RPM-based systems (Redhat-based)

1
yum install PyQt5

If you are new to Python PyQt, then I highly recommend this book.

  • Как установить proxmox на windows 10
  • Как установить proton vpn на windows
  • Как установить pyinstaller на windows
  • Как установить protobuf на windows
  • Как установить pycharm на windows 10 бесплатно