PySide/ru: Difference between revisions

From FreeCAD Documentation
(Created page with "Но предпочтителным методом будет создание UI объекта, который сразу будет включать все настройк...")
(Updating to match new version of source page)
(40 intermediate revisions by 3 users not shown)
Line 1: Line 1:
<languages/>
{{Note|PySide|Recently, FreeCAD has switched internally to use [http://qt-project.org/wiki/PySide PySide] instead of PyQt. That change was mainly done because of the licenses, PySide having an LGPL license which is more compatible with FreeeCAD. Other than that, PySide works exactly the same way as PyQt, and in FreeCAD you can usually use any of them, as you prefer. If you choose to use PySide, just replace all "PyQt" in the example code below with "PySide".<br />
{{docnav|Pivy|FeaturePython Objects}}
[http://qt-project.org/wiki/Differences_Between_PySide_and_PyQt Differences Between PySide and PyQt]}}


==Introduction==
[http://ru.wikipedia.org/wiki/PyQt PyQt] это модуль python, который позволяет приложениям на python создавать, получать доступ и изменять [http://ru.wikipedia.org/wiki/Qt Qt] приложения. Вы можете использовать его для создания собственных Qt программ на python, или получать доступ и изменять интерфейс запущенного qt приложения, такого как FreeCAD.


<div class="mw-translate-fuzzy">
Используя модуль PyQt внутри FreeCAD, дает вам полный контроль над вашим интерфейсом. Например вы можете:
[http://en.wikipedia.org/wiki/PySide PySide] это привязка Python кросс-платформенного инструментария GUI Qt. FreeCAD использует PySide для всех целей GUI (графический интерфейс пользователя) внутри Python. PySide является альтернативой пакету PyQt, который ранее использовался FreeCAD для своего графического интерфейса. PySide имеет более допустимую лицензию. Увидеть [http://qt-project.org/wiki/Differences_Between_PySide_and_PyQt Differences Between PySide and PyQt] для получения дополнительной информации о различиях.
* Добавить вашу панель,виджет или панель инструментов
</div>
* Добавить или убрать элементы с существующих панелей
* Изменить, перенаправить или добавить связи между всеми этими элементами


== PySide in FreeCAD with Qt5 ==
PyQt обладает обширной [http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html API документацией], и в сети существует множество руководств, которые научат вас как он работает.


FreeCAD was developed to be used with Python 2 and Qt4. As these two libraries became obsolete, FreeCAD transitioned to Python 3 and Qt5. In most cases this transition was done without needing to break backwards compatibility.
Если вы хотите работать над интерфейсом FreeCAD, первое что нужно сделать, это создать ссылку на главное окно FreeCAD:
<syntaxhighlight>
import sys
from PyQt4 import QtGui
app = QtGui.qApp
mw = app.activeWindow()
</syntaxhighlight>
Затем, вы можете, допустим, просмотреть все виджеты интерфеса:
<syntaxhighlight>
for child in mw.children():
print 'widget name = ', child.objectName(), ', widget type = ', child
</syntaxhighlight>
Виджеты в Qt интерфейсе как правило вложены в "контейнеры" виджетов, так что потомок нашего главного окна также может обладать потомками. В зависимости от типа виджета, есть множество вещей которые вы можете сделать. Свертесь с API документацией, чтобы понять, возможно ли это.


Normally, the {{incode|PySide}} module provides support for Qt4, while {{incode|PySide2}} provides support for Qt5. However, in FreeCAD, there is no need to use {{incode|PySide2}} directly, as a special {{incode|PySide}} module is included to handle Qt5.
Добавляем виджет, например dockWidget (который может быть размещен на одной из боковых панелей FreeCAD) просто:

<syntaxhighlight>
This {{incode|PySide}} module is located in the {{incode|Ext/}} directory of an installation of FreeCAD compiled for Qt5.
myWidget = QtGui.QDockWidget()
{{Code|code=
mw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myWidget)
/usr/share/freecad/Ext/PySide
</syntaxhighlight>
}}
Затем можно добавить чего нибудь напрямую в ваш виджет:

<syntaxhighlight>
This module just imports the necessary classes from {{incode|PySide2}}, but places them in the {{incode|PySide}} namespace. This means that in most cases the same code can be used with both Qt4 and Qt5, as long as it imports {{incode|PySide}}.
myWidget.setObjectName("my Nice New Widget")
{{Code|code=
myWidget.resize(QtCore.QSize(300,100)) # sets size of the widget
PySide2.QtCore -> PySide.QtCore
label = QtGui.QLabel("Hello World", myWidget) # creates a label
PySide2.QtGui -> PySide.QtGui
label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size
PySide2.QtSvg -> PySide.QtSvg
label.setObjectName("myLabel") # sets its name, so it can be found by name
PySide2.QtUiTools -> PySide.QtUiTools
</syntaxhighlight>
}}
Но предпочтителным методом будет создание UI объекта, который сразу будет включать все настройки вашего виджета. Главное преимущество в том что этот UI объект можно [[Dialog creation/ru|создать графически]] с помощью программы Qt Designer. Типичный объект созданый в Qt Designer , например этот:

<syntaxhighlight>
The only unusual aspect is that the {{incode|PySide2.QtWidgets}} classes are placed in the {{incode|PySide.QtGui}} namespace.
class myWidget_Ui(object):
{{Code|code=
def setupUi(self, myWidget):
PySide2.QtWidgets.QCheckBox -> PySide.QtGui.QCheckBox
myWidget.setObjectName("my Nice New Widget")
}}
myWidget.resize(QtCore.QSize(300,100).expandedTo(myWidget.minimumSizeHint())) # sets size of the widget

== PySide information ==
self.label = QtGui.QLabel(myWidget) # creates a label

self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size
Пользователи FreeCAD часто добиваются всего, используя встроенный интерфейс. Но для пользователей, которые хотят настроить свои операции, существует интерфейс Python, который описан в [[Python_scripting_tutorial | Python Scripting Tutorial]]. Интерфейс Python для FreeCAD обладает большой гибкостью и мощью. Для взаимодействия с пользователем Python с FreeCAD использует PySide, что описано на этой странице.
self.label.setObjectName("label") # sets its name, so it can be found by name

Python предлагает оператор 'print', который дает код:
def retranslateUi(self, draftToolbar): # built-in QT function that manages translations of widgets
{{Code|code=
myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
print 'Hello World'
self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))
}}
</syntaxhighlight>
С оператором 'print' Python вы имеете только ограниченный контроль над внешним видом и поведением. PySide предоставляет отсутствующий элемент управления, а также обрабатывает среды (такие как среда макрофайловых файлов FreeCAD), где встроенных средств Python недостаточно.
To use it, you just need to apply it to your freshly created widget like this:

<syntaxhighlight>
Возможности PySide варьируются от:
myNewFreeCADWidget = QtGui.QDockWidget() # create a new dckwidget

myNewFreeCADWidget.ui = myWidget_Ui() # load the Ui script
[[File:PySideScreenSnapshot1.jpg]]
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui

FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
до:
</syntaxhighlight>

[[File:PySideScreenSnapshot2.jpg]]

'''Familiarize yourself with some real-world examples of PySide'''
* [[PySide Beginner Examples]] (Hello World, announcements, enter text, enter number)
* [[PySide Intermediate Examples]] (window sizing, hiding widgets, popup menus, mouse position, mouse events)
* [[PySide Advanced Examples]] (widgets etc.)

They divide the subject matter into 3 parts, differentiated by level of exposure to PySide, Python and the FreeCAD internals. The first page has overview and background material giving a description of PySide and how it is put together while the second and third pages are mostly code examples at different levels.

The intention is that the associated pages will provide simple Python code to run PySide so that the user working on a problem can easily copy the code, paste it into their own work, adapt it as necessary and return to their problem solving with FreeCAD. Hopefully they don't have to go chasing off across the internet looking for answers to PySide questions. At the same time this page is not intended to replace the various comprehensive PySide tutorials and reference sites available on the web.

<div class="mw-translate-fuzzy">
{{docnav|Pivy|Scripted objects}}
{{docnav|Pivy|Scripted objects}}
</div>


{{Userdocnavi/ru}}
[[Category:Poweruser Documentation]]


[[Category:Poweruser Documentation/ru]]

[[Category:Developer/ru]]

[[Category:Developer Documentation/ru]]
{{clear}}
{{clear}}
<languages/>

Revision as of 22:59, 10 February 2020

Pivy
FeaturePython Objects

Introduction

PySide это привязка Python кросс-платформенного инструментария GUI Qt. FreeCAD использует PySide для всех целей GUI (графический интерфейс пользователя) внутри Python. PySide является альтернативой пакету PyQt, который ранее использовался FreeCAD для своего графического интерфейса. PySide имеет более допустимую лицензию. Увидеть Differences Between PySide and PyQt для получения дополнительной информации о различиях.

PySide in FreeCAD with Qt5

FreeCAD was developed to be used with Python 2 and Qt4. As these two libraries became obsolete, FreeCAD transitioned to Python 3 and Qt5. In most cases this transition was done without needing to break backwards compatibility.

Normally, the PySide module provides support for Qt4, while PySide2 provides support for Qt5. However, in FreeCAD, there is no need to use PySide2 directly, as a special PySide module is included to handle Qt5.

This PySide module is located in the Ext/ directory of an installation of FreeCAD compiled for Qt5.

/usr/share/freecad/Ext/PySide

This module just imports the necessary classes from PySide2, but places them in the PySide namespace. This means that in most cases the same code can be used with both Qt4 and Qt5, as long as it imports PySide.

PySide2.QtCore -> PySide.QtCore
PySide2.QtGui -> PySide.QtGui
PySide2.QtSvg -> PySide.QtSvg
PySide2.QtUiTools -> PySide.QtUiTools

The only unusual aspect is that the PySide2.QtWidgets classes are placed in the PySide.QtGui namespace.

PySide2.QtWidgets.QCheckBox -> PySide.QtGui.QCheckBox

PySide information

Пользователи FreeCAD часто добиваются всего, используя встроенный интерфейс. Но для пользователей, которые хотят настроить свои операции, существует интерфейс Python, который описан в Python Scripting Tutorial. Интерфейс Python для FreeCAD обладает большой гибкостью и мощью. Для взаимодействия с пользователем Python с FreeCAD использует PySide, что описано на этой странице.

Python предлагает оператор 'print', который дает код:

print 'Hello World'

С оператором 'print' Python вы имеете только ограниченный контроль над внешним видом и поведением. PySide предоставляет отсутствующий элемент управления, а также обрабатывает среды (такие как среда макрофайловых файлов FreeCAD), где встроенных средств Python недостаточно.

Возможности PySide варьируются от:

до:

Familiarize yourself with some real-world examples of PySide

They divide the subject matter into 3 parts, differentiated by level of exposure to PySide, Python and the FreeCAD internals. The first page has overview and background material giving a description of PySide and how it is put together while the second and third pages are mostly code examples at different levels.

The intention is that the associated pages will provide simple Python code to run PySide so that the user working on a problem can easily copy the code, paste it into their own work, adapt it as necessary and return to their problem solving with FreeCAD. Hopefully they don't have to go chasing off across the internet looking for answers to PySide questions. At the same time this page is not intended to replace the various comprehensive PySide tutorials and reference sites available on the web.

Pivy
Scripted objects