__init__.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright © 2009- The Spyder Development Team
  4. # Copyright © 2014-2015 Colin Duquesnoy
  5. #
  6. # Licensed under the terms of the MIT License
  7. # (see LICENSE.txt for details)
  8. """
  9. **QtPy** is a shim over the various Python Qt bindings. It is used to write
  10. Qt binding indenpendent libraries or applications.
  11. If one of the APIs has already been imported, then it will be used.
  12. Otherwise, the shim will automatically select the first available API (PyQt5,
  13. PySide2, PyQt4 and finally PySide); in that case, you can force the use of one
  14. specific bindings (e.g. if your application is using one specific bindings and
  15. you need to use library that use QtPy) by setting up the ``QT_API`` environment
  16. variable.
  17. PyQt5
  18. =====
  19. For PyQt5, you don't have to set anything as it will be used automatically::
  20. >>> from qtpy import QtGui, QtWidgets, QtCore
  21. >>> print(QtWidgets.QWidget)
  22. PySide2
  23. ======
  24. Set the QT_API environment variable to 'pyside2' before importing other
  25. packages::
  26. >>> import os
  27. >>> os.environ['QT_API'] = 'pyside2'
  28. >>> from qtpy import QtGui, QtWidgets, QtCore
  29. >>> print(QtWidgets.QWidget)
  30. PyQt4
  31. =====
  32. Set the ``QT_API`` environment variable to 'pyqt' before importing any python
  33. package::
  34. >>> import os
  35. >>> os.environ['QT_API'] = 'pyqt'
  36. >>> from qtpy import QtGui, QtWidgets, QtCore
  37. >>> print(QtWidgets.QWidget)
  38. PySide
  39. ======
  40. Set the QT_API environment variable to 'pyside' before importing other
  41. packages::
  42. >>> import os
  43. >>> os.environ['QT_API'] = 'pyside'
  44. >>> from qtpy import QtGui, QtWidgets, QtCore
  45. >>> print(QtWidgets.QWidget)
  46. """
  47. from distutils.version import LooseVersion
  48. import os
  49. import platform
  50. import sys
  51. import warnings
  52. # Version of QtPy
  53. from ._version import __version__
  54. class PythonQtError(RuntimeError):
  55. """Error raise if no bindings could be selected."""
  56. pass
  57. class PythonQtWarning(Warning):
  58. """Warning if some features are not implemented in a binding."""
  59. pass
  60. # Qt API environment variable name
  61. QT_API = 'QT_API'
  62. # Names of the expected PyQt5 api
  63. PYQT5_API = ['pyqt5']
  64. # Names of the expected PyQt4 api
  65. PYQT4_API = [
  66. 'pyqt', # name used in IPython.qt
  67. 'pyqt4' # pyqode.qt original name
  68. ]
  69. # Names of the expected PySide api
  70. PYSIDE_API = ['pyside']
  71. # Names of the expected PySide2 api
  72. PYSIDE2_API = ['pyside2']
  73. # Detecting if a binding was specified by the user
  74. binding_specified = QT_API in os.environ
  75. # Setting a default value for QT_API
  76. os.environ.setdefault(QT_API, 'pyqt5')
  77. API = os.environ[QT_API].lower()
  78. initial_api = API
  79. assert API in (PYQT5_API + PYQT4_API + PYSIDE_API + PYSIDE2_API)
  80. is_old_pyqt = is_pyqt46 = False
  81. PYQT5 = True
  82. PYQT4 = PYSIDE = PYSIDE2 = False
  83. # When `FORCE_QT_API` is set, we disregard
  84. # any previously imported python bindings.
  85. if os.environ.get('FORCE_QT_API') is not None:
  86. if 'PyQt5' in sys.modules:
  87. API = initial_api if initial_api in PYQT5_API else 'pyqt5'
  88. elif 'PySide2' in sys.modules:
  89. API = initial_api if initial_api in PYSIDE2_API else 'pyside2'
  90. elif 'PyQt4' in sys.modules:
  91. API = initial_api if initial_api in PYQT4_API else 'pyqt4'
  92. elif 'PySide' in sys.modules:
  93. API = initial_api if initial_api in PYSIDE_API else 'pyside'
  94. if API in PYQT5_API:
  95. try:
  96. from PyQt5.QtCore import PYQT_VERSION_STR as PYQT_VERSION # analysis:ignore
  97. from PyQt5.QtCore import QT_VERSION_STR as QT_VERSION # analysis:ignore
  98. PYSIDE_VERSION = None
  99. if sys.platform == 'darwin':
  100. macos_version = LooseVersion(platform.mac_ver()[0])
  101. if macos_version < LooseVersion('10.10'):
  102. if LooseVersion(QT_VERSION) >= LooseVersion('5.9'):
  103. raise PythonQtError("Qt 5.9 or higher only works in "
  104. "macOS 10.10 or higher. Your "
  105. "program will fail in this "
  106. "system.")
  107. elif macos_version < LooseVersion('10.11'):
  108. if LooseVersion(QT_VERSION) >= LooseVersion('5.11'):
  109. raise PythonQtError("Qt 5.11 or higher only works in "
  110. "macOS 10.11 or higher. Your "
  111. "program will fail in this "
  112. "system.")
  113. del macos_version
  114. except ImportError:
  115. API = os.environ['QT_API'] = 'pyside2'
  116. if API in PYSIDE2_API:
  117. try:
  118. from PySide2 import __version__ as PYSIDE_VERSION # analysis:ignore
  119. from PySide2.QtCore import __version__ as QT_VERSION # analysis:ignore
  120. PYQT_VERSION = None
  121. PYQT5 = False
  122. PYSIDE2 = True
  123. if sys.platform == 'darwin':
  124. macos_version = LooseVersion(platform.mac_ver()[0])
  125. if macos_version < LooseVersion('10.11'):
  126. if LooseVersion(QT_VERSION) >= LooseVersion('5.11'):
  127. raise PythonQtError("Qt 5.11 or higher only works in "
  128. "macOS 10.11 or higher. Your "
  129. "program will fail in this "
  130. "system.")
  131. del macos_version
  132. except ImportError:
  133. API = os.environ['QT_API'] = 'pyqt'
  134. if API in PYQT4_API:
  135. try:
  136. import sip
  137. try:
  138. sip.setapi('QString', 2)
  139. sip.setapi('QVariant', 2)
  140. sip.setapi('QDate', 2)
  141. sip.setapi('QDateTime', 2)
  142. sip.setapi('QTextStream', 2)
  143. sip.setapi('QTime', 2)
  144. sip.setapi('QUrl', 2)
  145. except (AttributeError, ValueError):
  146. # PyQt < v4.6
  147. pass
  148. from PyQt4.Qt import PYQT_VERSION_STR as PYQT_VERSION # analysis:ignore
  149. from PyQt4.Qt import QT_VERSION_STR as QT_VERSION # analysis:ignore
  150. PYSIDE_VERSION = None
  151. PYQT5 = False
  152. PYQT4 = True
  153. except ImportError:
  154. API = os.environ['QT_API'] = 'pyside'
  155. else:
  156. is_old_pyqt = PYQT_VERSION.startswith(('4.4', '4.5', '4.6', '4.7'))
  157. is_pyqt46 = PYQT_VERSION.startswith('4.6')
  158. if API in PYSIDE_API:
  159. try:
  160. from PySide import __version__ as PYSIDE_VERSION # analysis:ignore
  161. from PySide.QtCore import __version__ as QT_VERSION # analysis:ignore
  162. PYQT_VERSION = None
  163. PYQT5 = PYSIDE2 = False
  164. PYSIDE = True
  165. except ImportError:
  166. raise PythonQtError('No Qt bindings could be found')
  167. # If a correct API name is passed to QT_API and it could not be found,
  168. # switches to another and informs through the warning
  169. if API != initial_api and binding_specified:
  170. warnings.warn('Selected binding "{}" could not be found, '
  171. 'using "{}"'.format(initial_api, API), RuntimeWarning)
  172. API_NAME = {'pyqt5': 'PyQt5', 'pyqt': 'PyQt4', 'pyqt4': 'PyQt4',
  173. 'pyside': 'PySide', 'pyside2':'PySide2'}[API]
  174. if PYQT4:
  175. import sip
  176. try:
  177. API_NAME += (" (API v{0})".format(sip.getapi('QString')))
  178. except AttributeError:
  179. pass