def test_sip_api_qtpy(): """Preferred binding PyQt4 should have sip version 2""" __import__("Qt") # Bypass linter warning import sip assert sip.getapi("QString") == 2, ("PyQt4 API version should be 2, " "instead is %s" % sip.getapi("QString"))
def _initPyQt4(): """initialize PyQt4 to be compatible with PySide""" import sip if 'PyQt4.QtCore' in sys.modules: # too late to configure API, let's check that it was properly parameterized... for api in ('QVariant', 'QString'): if sip.getapi(api) != 2: raise RuntimeError('%s API already set to V%d, but should be 2' % (api, sip.getapi(api))) else: sip.setapi("QString", 2) sip.setapi("QVariant", 2)
def import_pyqt4(version=2): """ Import PyQt4 Parameters ---------- version : 1, 2, or None Which QString/QVariant API to use. Set to None to use the system default ImportErrors rasied within this function are non-recoverable """ # The new-style string API (version=2) automatically # converts QStrings to Unicode Python strings. Also, automatically unpacks # QVariants to their underlying objects. import sip if version is not None: sip.setapi('QString', version) sip.setapi('QVariant', version) from PyQt4 import QtGui, QtCore, QtSvg if not check_version(QtCore.PYQT_VERSION_STR, '4.7'): raise ImportError("QtConsole requires PyQt4 >= 4.7, found %s" % QtCore.PYQT_VERSION_STR) # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # query for the API version (in case version == None) version = sip.getapi('QString') api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT return QtCore, QtGui, QtSvg, api
def check_pyqt4_api(): """If PyQt4 was already imported before we got a chance to set API version 2, ensure the API versions are either not set, or set to version 2. Otherwise confusing errors may occur later - better to catch this now""" import sip API_NAMES = [ "QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant" ] API_VERSION = 2 for name in API_NAMES: try: if sip.getapi(name) != API_VERSION: msg = ( "qtutils is only compatible with version 2 of the PyQt4 API." + "Whilst you can import PyQt4 prior to importing qtutils (in order to tell qtutils " + "to use PyQt4), either set the API version to 2 yourself, or import qtutils " + "(which will set it for you) prior to importing QtGui or QtCore." ) raise RuntimeError(msg) except ValueError: # API version not set yet. pass
def import_pyqt4(version=2): """ Import PyQt4 Parameters ---------- version : 1, 2, or None Which QString/QVariant API to use. Set to None to use the system default ImportErrors rasied within this function are non-recoverable """ # The new-style string API (version=2) automatically # converts QStrings to Unicode Python strings. Also, automatically unpacks # QVariants to their underlying objects. import sip if version is not None: sip.setapi('QString', version) sip.setapi('QVariant', version) from PyQt4 import QtGui, QtCore, QtSvg if not check_version(QtCore.PYQT_VERSION_STR, '4.7'): raise ImportError("IPython requires PyQt4 >= 4.7, found %s" % QtCore.PYQT_VERSION_STR) # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # query for the API version (in case version == None) version = sip.getapi('QString') api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT return QtCore, QtGui, QtSvg, api
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/geometry_copier" # initialize locale locale_path = "" if sip.getapi("QVariant") > 1: # new API style locale = QSettings().value("locale/userLocale")[0:2] else: # the old API style locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): locale_path = self.plugin_dir + "/i18n/geometry_copier_" + locale + ".qm" if QFileInfo(locale_path).exists(): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self._geom_buffer = None
def __setPyQt4API(element, api_version=2): try: ver = sip.getapi(element) except ValueError: ver = -1 if ver < 0: try: sip.setapi(element, api_version) log.debug("%s API set to version %d", element, sip.getapi("QString")) except ValueError: log.warning("Error setting %s API to version %s", element, api_version, exc_info=1) return False elif ver < api_version: log.info("%s API set to version %s (advised: version >= %s)", element, ver, api_version) return True
def sip_getapi(name): """ Get the api version for a name. """ if sip.SIP_VERSION > 0x40900: return sip.getapi(name) elif name in _API_NAMES: return 1 else: raise ValueError("unknown API {0!r}".format(name))
def _pyqt4(): """Initialise PyQt4""" import sip # Validation of envivornment variable. Prevents an error if # the variable is invalid since it's just a hint. try: hint = int(QT_SIP_API_HINT) except TypeError: hint = None # Variable was None, i.e. not set. except ValueError: raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2") for api in ("QString", "QVariant", "QDate", "QDateTime", "QTextStream", "QTime", "QUrl"): try: sip.setapi(api, hint or 2) except AttributeError: raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py") except ValueError: actual = sip.getapi(api) if not hint: raise ImportError("API version already set to %d" % actual) else: # Having provided a hint indicates a soft constraint, one # that doesn't throw an exception. sys.stderr.write( "Warning: API '%s' has already been set to %d.\n" % (api, actual)) import PyQt4 as module _setup(module, ["uic"]) if hasattr(Qt, "_uic"): Qt.QtCompat.loadUi = _loadUi if hasattr(Qt, "_QtGui"): setattr(Qt, "QtWidgets", _new_module("QtWidgets")) setattr(Qt, "_QtWidgets", Qt._QtGui) Qt.QtCompat.setSectionResizeMode = \ Qt._QtGui.QHeaderView.setResizeMode if hasattr(Qt, "_QtCore"): Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR QCoreApplication = Qt._QtCore.QCoreApplication Qt.QtCompat.translate = ( lambda context, sourceText, disambiguation, n: QCoreApplication. translate(context, sourceText, disambiguation, QCoreApplication. CodecForTr, n)) _reassign_misplaced_members("pyqt4")
def uni(s, encoding='gbk'): if sip.getapi('QString') != 2: # api=2时QString会自动变为str类型 if isinstance(s, QtCore.QString): s = unicode(s) if isinstance(s, unicode): return s elif isinstance(s, str): return unicode(s, encoding) else: return unicode(s)
def load_Qt4(): from PyQt4 import QtGui, QtCore # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot version = sip.getapi('QString') api = 'pyqt4' if version == 1 else 'pyqt4v2' return QtCore, QtGui, api
def uni(s, encoding="gbk"): if sip.getapi("QString") != 2: # api=2时QString会自动变为str类型 if isinstance(s, QtCore.QString): s = unicode(s) if isinstance(s, unicode): return s elif isinstance(s, str): return unicode(s, encoding) else: return unicode(s)
def requireCompatibleAPI(): """If PyQt4's API should be configured to be compatible with PySide's (i.e. QString and QVariant should not be explicitly exported, cf. documentation of sip.setapi()), call this function to check that the PyQt4 was properly imported. (It will always be configured this way by this module, but it could have been imported before we got a hand on doing so.) """ if 'PyQt4.QtCore' in sys.modules: import sip for api in ('QVariant', 'QString'): if sip.getapi(api) != 2: raise RuntimeError('%s API already set to V%d, but should be 2' % (api, sip.getapi(api)))
def utf8(u, encoding='gbk'): ''' string convert (gbk -> utf-8) ''' if sip.getapi('QString') != 2: # api=2时QString会自动变为str类型 if isinstance(u, QtCore.QString): u = unicode(u) if isinstance(u, unicode): return u.encode('utf-8') elif encoding == 'utf-8': return u else: return unicode(u, encoding).encode('utf-8')
def utf8(u, encoding="gbk"): ''' string convert (gbk -> utf-8) ''' if sip.getapi("QString") != 2: # api=2时QString会自动变为str类型 if isinstance(u, QtCore.QString): u = unicode(u) if isinstance(u, unicode): return u.encode("utf-8") elif encoding == "utf-8": return u else: return unicode(u, encoding).encode("utf-8")
def qtapi_version(): """Return which QString API has been set, if any Returns ------- The QString API version (1 or 2), or None if not set """ try: import sip except ImportError: return try: return sip.getapi('QString') except ValueError: return
def run(self): # show the dialog self.dlg.show() text = self.dlg.ui.text text.append("QGIS " + QGis.QGIS_VERSION) text.append("SIP " + sip.SIP_VERSION_STR + " API V" + str(sip.getapi("QVariant"))) text.append("\n") tests = unittest.TestSuite([unittest.TestLoader().loadTestsFromTestCase(TestQvariant), unittest.TestLoader().loadTestsFromTestCase(TestQstring), unittest.TestLoader().loadTestsFromTestCase(TestVectorapi)]) unittest.TextTestRunner(verbosity=2, stream=self.dlg).run(tests) # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result == 1: pass
def __init__(self): """Constructor""" # Determine the sip api that is used, because this depends on whether # or not IPython is loaded object.__setattr__(self, u'api', sip.getapi(u'QString')) if self.api not in (1, 2): raise Exception(u'config: unknown api %s' % self.api) # Apply OS specific override settings if platform.system() == u"Windows": for key, value in self.config_windows.iteritems(): self.config[key] = value elif platform.system() == u"Darwin": for key, value in self.config_mac.iteritems(): self.config[key] = value elif platform.system() == u"Linux": for key, value in self.config_linux.iteritems(): self.config[key] = value
def qtapi_version(): """Return which QString API has been set, if any Returns ------- The QString API version (1 or 2), or None if not set """ try: import sip except ImportError: # as of PyQt5 5.11, sip is no longer available as a top-level # module and needs to be imported from the PyQt5 namespace try: from PyQt5 import sip except ImportError: return try: return sip.getapi('QString') except ValueError: return
def __init__(self): """Constructor""" # Determine the sip api that is used, because this depends on whether # or not IPython is loaded object.__setattr__(self, u'api', sip.getapi(u'QString')) if self.api not in (1,2): raise Exception(u'config: unknown api %s' % self.api) # Apply OS specific override settings if platform.system() == u"Windows": for key, value in self.config_windows.iteritems(): self.config[key] = value elif platform.system() == u"Darwin": for key, value in self.config_mac.iteritems(): self.config[key] = value elif platform.system() == u"Linux": for key, value in self.config_linux.iteritems(): self.config[key] = value
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/geometry_copier" # initialize locale locale_path = "" if sip.getapi("QVariant") > 1: # new API style locale = QSettings().value("locale/userLocale")[0:2] else: # the old API style locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): locale_path = self.plugin_dir + "/i18n/geometry_copier_" + locale + ".qm" if QFileInfo(locale_path).exists(): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self._geom_buffer = None
import sys import collections from guidata.qt.QtGui import QFileDialog from guidata.py3compat import is_text_string, to_text_string, TEXT_TYPES #============================================================================== # QVariant conversion utilities #============================================================================== PYQT_API_1 = False if os.environ['QT_API'] == 'pyqt': import sip try: PYQT_API_1 = sip.getapi('QVariant') == 1 # PyQt API #1 except AttributeError: # PyQt <v4.6 PYQT_API_1 = True def to_qvariant(pyobj=None): """Convert Python object to QVariant This is a transitional function from PyQt API #1 (QVariant exist) to PyQt API #2 and Pyside (QVariant does not exist)""" if PYQT_API_1: # PyQt API #1 from PyQt4.QtCore import QVariant return QVariant(pyobj) else: # PyQt API #2 return pyobj
if QT_API == QT_API_PYQT5: try: from PyQt5 import QtCore, QtGui, QtWidgets _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName except ImportError: # fell through, tried PyQt5, failed fall back to PyQt4 QT_API = rcParams['backend.qt4'] QT_RC_MAJOR_VERSION = 4 # needs to be if so we can re-test the value of QT_API which may # have been changed in the above if block if QT_API in [QT_API_PYQT, QT_API_PYQTv2]: # PyQt4 API from PyQt4 import QtCore, QtGui try: if sip.getapi("QString") > 1: # Use new getSaveFileNameAndFilter() _getSaveFileName = QtGui.QFileDialog.getSaveFileNameAndFilter else: # Use old getSaveFileName() def _getSaveFileName(*args, **kwargs): return (QtGui.QFileDialog.getSaveFileName(*args, **kwargs), None) except (AttributeError, KeyError): # call to getapi() can fail in older versions of sip def _getSaveFileName(*args, **kwargs): return QtGui.QFileDialog.getSaveFileName(*args, **kwargs), None
if __name__ != "__main__": print "Console Player must be started as the main script" sys.exit(1) isPosix = os.name == "posix" __debug = "-debug" in sys.argv __devmode = "-devmode" in sys.argv __install = "-install" in sys.argv # launch with the -install flag to reinstall the application __install_home = "--install=home" in sys.argv # force install to home directort. try: cur_api_ver = sip.getapi("QString") # raises an exception when not set except: cur_api_ver = 0 finally: # For Python 2.7, PyInstaller # error: http://www.pyinstaller.org/ticket/159 # if you want to use PyInstaller, find this file: # %PyInstaller%/support/rthooks/pyi_rth_qt4plugins.py # and add this API changing code at the top of it: # you do not need the api check i do above. # In python 3, the default is API-2 if cur_api_ver != 2: API_NAMES = ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"] API_VERSION = 2 for name in API_NAMES: sip.setapi(name, API_VERSION)
from openalea.plantgl.all import get_pgl_qt_version import os QT_VERSION = get_pgl_qt_version() >> 16 os.environ['QT_API'] = 'pyqt' if QT_VERSION == 4 else 'pyqt' + str(QT_VERSION) if QT_VERSION == 4: os.environ.setdefault('QT_API_VERSION', '2') from openalea.vpltk import qt if QT_VERSION == 4: import sip assert sip.getapi('QString') == 2
try: from PySide import __version__ as PYSIDE_VERSION # analysis:ignore from PySide.QtCore import __version__ as QT_VERSION # analysis:ignore PYQT_VERSION = None PYQT5 = PYSIDE2 = False PYSIDE = True except ImportError: raise PythonQtError('No Qt bindings could be found') # If a correct API name is passed to QT_API and it could not be found, # switches to another and informs through the warning if API != initial_api and binding_specified: warnings.warn( 'Selected binding "{}" could not be found, ' 'using "{}"'.format(initial_api, API), RuntimeWarning) API_NAME = { 'pyqt5': 'PyQt5', 'pyqt': 'PyQt4', 'pyqt4': 'PyQt4', 'pyside': 'PySide', 'pyside2': 'PySide2' }[API] if PYQT4: import sip try: API_NAME += (" (API v{0})".format(sip.getapi('QString'))) except AttributeError: pass
# try: # sip.setapi('QString', 2) # sip.setapi('QVariant', 2) # except AttributeError: # # PyQt < v4.6: in future version, we should warn the user # # that PyQt is outdated and won't be supported by Spyder >v2.1 # pass try: from PyQt4.QtCore import PYQT_VERSION_STR as __version__ except ImportError: # Switching to PySide API = os.environ['QT_API'] = 'pyside' API_NAME = 'PySide' else: __version_info__ = tuple(__version__.split('.')+['final', 1]) is_old_pyqt = __version__.startswith(('4.4', '4.5', '4.6', '4.7')) is_pyqt46 = __version__.startswith('4.6') import sip try: API_NAME += (" (API v%d)" % sip.getapi('QString')) except AttributeError: pass if API == 'pyside': try: from PySide import __version__ # analysis:ignore except ImportError: raise ImportError("Spyder requires PySide or PyQt to be installed") else: is_old_pyqt = is_pyqt46 = False
# In case this function is not used properly, this could happen return obj else: return str(obj, encoding) #============================================================================== # QVariant conversion utilities #============================================================================== PYQT_API_1 = False import collections if os.environ.get('QT_API', 'pyqt') == 'pyqt': import sip if QT_API == "PYQT4": try: PYQT_API_1 = sip.getapi('QVariant') == 1 except AttributeError: PYQT_API_1 = True def to_qvariant(pyobj=None): """Convert Python object to QVariant This is a transitional function from PyQt API #1 (QVariant exist) to PyQt API #2 and Pyside (QVariant does not exist)""" if PYQT_API_1: from code_saturne.Base.QtCore import QVariant return QVariant(pyobj) else: return pyobj def from_qvariant(qobj=None, convfunc=None): """Convert QVariant object to Python object
Dynamic editor class Class changes appearance according to provide edf-xml document """ # required to get the Python 2 behavior of QT # see https://stackoverflow.com/a/21223060 import sip qt4 = False try: from PyQt4 import QtGui from PyQt4.QtGui import QFont from PyQt4.QtGui import QFontMetrics from PyQt4 import QtXml from PyQt4 import QtCore if sip.getapi('QVariant') == 1: qt4 = True except ImportError: from PyQt5 import QtWidgets as QtGui from PyQt5.QtGui import QFont from PyQt5.QtGui import QFontMetrics from PyQt5 import QtXml from PyQt5 import QtCore class MatTypes(): """Enumeration class for signals""" MAT_APPLY = 1 MAT_OK = 2 MAT_NEW = 3 MAT_DELETE = 4
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenSesame. If not, see <http://www.gnu.org/licenses/>. """ from PyQt4 import QtCore import libopensesame.misc from libopensesame import debug # Determine the sip api that is used, because this depends on whether or not # IPython is loaded import sip api = sip.getapi('QString') if api not in (1,2): raise Exception('config: unknown api %s' % api) config = { "cfg_ver" : 0, "_initial_window_state" : QtCore.QByteArray(), "auto_update_check" : True, "auto_response" : False, "autosave_interval" : 10 * 60 * 1000, "autosave_max_age" : 7, "default_logfile_folder" : libopensesame.misc.home_folder(), "disabled_plugins" : "", "immediate_rename" : False, "onetabmode" : False, "overview_info" : False,
Originally distributed under MIT/X11 license. See documentation/MITLicense.txt for more infomation. """ __version__ = '0.1' import os import sys # If we are using PyQt, ACQ4 requires API version 2 for QString and QVariant. # Check for those here.. set_api = True if 'PyQt4' in sys.modules: import sip for api in ['QString', 'QVariant']: try: v = sip.getapi(api) if v != 2: raise Exception("We require the usage of API version 2 for " "QString and QVariant, but {0}={1}. " "Correct this by calling\n\n import sip;\n " "sip.setapi('QString', 2);\n " "sip.setapi('QVariant', 2);\n\n " "_before_ importing PyQt4.".format(str(api),str(v)) ) else: set_api = False except ValueError: set_api = True elif 'PySide' in sys.modules: set_api = False
# Alias PyQt-specific functions for PySide compatibility. if hasattr(__QtCore, "pyqtSignal"): Signal = __QtCore.pyqtSignal if hasattr(__QtCore, "pyqtSlot"): Slot = __QtCore.pyqtSlot if hasattr(__QtCore, "pyqtProperty"): Property = __QtCore.pyqtProperty try: __api_version__ = __QtCore.QT_VERSION_STR except AttributeError: pass try: import sip PYQT_QVARIANT_API_1 = sip.getapi('QVariant') < 2 PYQT_QSTRING_API_1 = sip.getapi('QString') < 2 except (ImportError, AttributeError): PYQT_QVARIANT_API_1 = True PYQT_QSTRING_API_1 = True if PYQT_QVARIANT_API_1: to_qvariant = __to_qvariant_1 from_qvariant = __from_qvariant_1 else: __QtCore.QVariant = QVariant = __QVariant_2 to_qvariant = __to_qvariant_2 from_qvariant = __from_qvariant_2 if not PYQT_QSTRING_API_1:
import sip import qtpy __all__ = [ 'getQVariantValue', 'wheelAngleDelta', ] try: if qtpy.PYQT5: QVARIANT_API = 2 else: QVARIANT_API = sip.getapi('QVariant') except ValueError: QVARIANT_API = 1 if QVARIANT_API == 1: def getQVariantValue(variant): return variant.toPyObject() else: def getQVariantValue(variant): return variant if qtpy.PYQT5: def wheelAngleDelta(wheelEvent): return wheelEvent.angleDelta().y() else:
# Trying PyQt5 before switching to PySide (at this point, PyQt4 may # not be installed but PyQt5 or Pyside could still be if the QT_API # environment variable hasn't been set-up) try: import PyQt5 # analysis:ignore API = os.environ['QT_API'] = 'pyqt5' API_NAME = 'PyQt5' except ImportError: API = os.environ['QT_API'] = 'pyside' API_NAME = 'PySide' else: is_old_pyqt = __version__.startswith(('4.4', '4.5', '4.6', '4.7')) is_pyqt46 = __version__.startswith('4.6') import sip try: API_NAME += (" (API v%d)" % sip.getapi('QString')) except AttributeError: pass from PyQt4 import uic # analysis:ignore PYQT5 = False if API == 'pyqt5': try: from PyQt5.QtCore import PYQT_VERSION_STR as __version__ from PyQt5 import uic # analysis:ignore PYQT5 = True is_old_pyqt = is_pyqt46 = False except ImportError: pass if API == 'pyside':
def isSIPv2(): return sip.getapi('QVariant') > 1
print config.get_config('my_setting') New style: from libqtopensesame.misc.config import cfg cfg.my_setting = 'my_value' # set print cfg.my_setting # get """ from libopensesame.exceptions import osexception from PyQt4 import QtCore import libopensesame.misc from libopensesame import debug import platform import sip if sip.getapi(u'QString') == 2: QtCore.QStringList = list class config(object): config = { u"cfg_ver" : 0, u"_initial_window_geometry" : QtCore.QByteArray(), u"_initial_window_state" : QtCore.QByteArray(), u"auto_update_check" : True, u"auto_response" : False, u"autosave_interval" : 10 * 60 * 1000, u"autosave_max_age" : 7, u"default_logfile_folder" : libopensesame.misc.home_folder(), u"default_pool_folder" : libopensesame.misc.home_folder(),
API = os.environ['QT_API'] = 'pyside' else: is_old_pyqt = PYQT_VERSION.startswith(('4.4', '4.5', '4.6', '4.7')) is_pyqt46 = PYQT_VERSION.startswith('4.6') if API in PYSIDE_API: try: from PySide import __version__ as PYSIDE_VERSION # analysis:ignore from PySide.QtCore import __version__ as QT_VERSION # analysis:ignore PYQT_VERSION = None PYQT5 = PYSIDE2 = False PYSIDE = True except ImportError: raise PythonQtError('No Qt bindings could be found') # If a correct API name is passed to QT_API and it could not be found, # switches to another and informs through the warning if API != initial_api: warnings.warn('Selected binding "{}" could not be found, ' 'using "{}"'.format(initial_api, API), RuntimeWarning) API_NAME = {'pyqt5': 'PyQt5', 'pyqt': 'PyQt4', 'pyqt4': 'PyQt4', 'pyside': 'PySide', 'pyside2':'PySide2'}[API] if PYQT4: import sip try: API_NAME += (" (API v{0})".format(sip.getapi('QString'))) except AttributeError: pass
def isSIPv2(): '''Checks the version of SIP ''' return sip.getapi('QVariant') > 1
#try: sip.setapi('QString', 2) sip.setapi('QVariant', 2) Ipython = True #except ValueError: from PyQt4 import QtCore, QtGui from matplotlib import pyplot from OpenElectrophy import * from scipy import * app = QtGui.QApplication(sys.argv) if sip.getapi('QString') == 1: msgBox = QtGui.QMessageBox() msgBox.setText(""" <b>API Error</b> <p>API 'QString' has already been set to version 1 <p>Ipython will not work. You can change this option in <b>Spyder->Tools-->Preference->External Module->PyQt->API #2</b> <p>SynaptiQs will now start without Ipython """) msgBox.exec_() Ipython = False import sys, os, atexit, glob, warnings from matplotlib import * #warnings.filterwarnings("ignore", category=DeprecationWarning)
def _pyqt4(): """Initialise PyQt4""" import sip # Validation of envivornment variable. Prevents an error if # the variable is invalid since it's just a hint. try: hint = int(QT_SIP_API_HINT) except TypeError: hint = None # Variable was None, i.e. not set. except ValueError: raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2") for api in ("QString", "QVariant", "QDate", "QDateTime", "QTextStream", "QTime", "QUrl"): try: sip.setapi(api, hint or 2) except AttributeError: raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py") except ValueError: actual = sip.getapi(api) if not hint: raise ImportError("API version already set to %d" % actual) else: # Having provided a hint indicates a soft constraint, one # that doesn't throw an exception. sys.stderr.write( "Warning: API '%s' has already been set to %d.\n" % (api, actual) ) import PyQt4 as module _setup(module, ["uic"]) try: import sip Qt.QtCompat.wrapInstance = ( lambda ptr, base=None: _wrapinstance( sip.wrapinstance, ptr, base) ) Qt.QtCompat.getCppPointer = lambda object: \ sip.unwrapinstance(object) except ImportError: pass # Optional if hasattr(Qt, "_uic"): Qt.QtCompat.loadUi = _loadUi if hasattr(Qt, "_QtGui"): setattr(Qt, "QtWidgets", _new_module("QtWidgets")) setattr(Qt, "_QtWidgets", Qt._QtGui) if hasattr(Qt._QtGui, "QX11Info"): setattr(Qt, "QtX11Extras", _new_module("QtX11Extras")) Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info Qt.QtCompat.setSectionResizeMode = \ Qt._QtGui.QHeaderView.setResizeMode if hasattr(Qt, "_QtCore"): Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR QCoreApplication = Qt._QtCore.QCoreApplication Qt.QtCompat.translate = ( lambda context, sourceText, disambiguation, n: QCoreApplication.translate( context, sourceText, disambiguation, QCoreApplication.CodecForTr, n) ) _reassign_misplaced_members("PyQt4") # QFileDialog QtCompat decorator def _standardizeQFileDialog(some_function): """Decorator that makes PyQt4 return conform to other bindings""" def wrapper(*args, **kwargs): ret = (some_function(*args, **kwargs)) # PyQt4 only returns the selected filename, force it to a # standard return of the selected filename, and a empty string # for the selected filter return ret, '' wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper decorators = { "QFileDialog": { "getOpenFileName": _standardizeQFileDialog, "getOpenFileNames": _standardizeQFileDialog, "getSaveFileName": _standardizeQFileDialog, } } _build_compatibility_members('PyQt4', decorators)
def isSIPv2(): return sip.getapi("QVariant") > 1
>>> config.set_config('my_setting', 'my_value') >>> print config.get_config('my_setting') NEW STYLE ========= >>> from libqtopensesame.misc.config import cfg >>> cfg.my_setting = 'my_value' # set >>> print cfg.my_setting # get """ from PyQt4 import QtCore import libopensesame.misc from libopensesame import debug, exceptions import platform import sip if sip.getapi(u'QString') == 2: QtCore.QStringList = list class config(object): config = { u"cfg_ver" : 0, u"_initial_window_geometry" : QtCore.QByteArray(), u"_initial_window_state" : QtCore.QByteArray(), u"auto_update_check" : True, u"auto_response" : False, u"autosave_interval" : 10 * 60 * 1000, u"autosave_max_age" : 7, u"default_logfile_folder" : libopensesame.misc.home_folder(), u"default_pool_folder" : libopensesame.misc.home_folder(), u"disabled_plugins" : "",
from PyQt4.QtCore import (QCoreApplication, QUrl, QObject) from qgis.core import (QgsProviderRegistry, QgsVectorLayer, QgsFeatureRequest, QgsRectangle, QgsMessageLog) from utilities import (getQgisTestApp, TestCase, unitTestDataPath, unittest, compareWkt) from providertestbase import ProviderTestCase QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp() TEST_DATA_DIR = unitTestDataPath() import sip sipversion = str(sip.getapi('QVariant')) sipwanted = '2' geomkey = "#geometry" fidkey = "#fid" # Thought we could connect to messageReceived signal but doesn't seem to be available # in python :-( Not sure why? class MessageLogger(QObject): def __init__(self, tag=None): QObject.__init__(self) self.log = [] self.tag = tag def __enter__(self):
def sipv1(): return sip.getapi("QVariant") == 1
) from utilities import (getQgisTestApp, TestCase, unitTestDataPath, unittest, compareWkt ) from providertestbase import ProviderTestCase QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp() TEST_DATA_DIR = unitTestDataPath() import sip sipversion = str(sip.getapi('QVariant')) sipwanted = '2' geomkey = "#geometry" fidkey = "#fid" # Thought we could connect to messageReceived signal but doesn't seem to be available # in python :-( Not sure why? class MessageLogger(QObject): def __init__(self, tag=None): QObject.__init__(self) self.log = [] self.tag = tag
def _pyqt4(): """Initialise PyQt4""" import sip # Validation of envivornment variable. Prevents an error if # the variable is invalid since it's just a hint. try: hint = int(QT_SIP_API_HINT) except TypeError: hint = None # Variable was None, i.e. not set. except ValueError: raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2") for api in ("QString", "QVariant", "QDate", "QDateTime", "QTextStream", "QTime", "QUrl"): try: sip.setapi(api, hint or 2) except AttributeError: raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py") except ValueError: actual = sip.getapi(api) if not hint: raise ImportError("API version already set to %d" % actual) else: # Having provided a hint indicates a soft constraint, one # that doesn't throw an exception. sys.stderr.write( "Warning: API '%s' has already been set to %d.\n" % (api, actual)) import PyQt4 as module _setup(module, ["uic"]) try: import sip Qt.QtCompat.wrapInstance = ( lambda ptr, base=None: _wrapinstance(sip.wrapinstance, ptr, base)) Qt.QtCompat.getCppPointer = lambda object: \ sip.unwrapinstance(object) except ImportError: pass # Optional if hasattr(Qt, "_uic"): Qt.QtCompat.loadUi = _loadUi if hasattr(Qt, "_QtGui"): setattr(Qt, "QtWidgets", _new_module("QtWidgets")) setattr(Qt, "_QtWidgets", Qt._QtGui) Qt.QtCompat.setSectionResizeMode = \ Qt._QtGui.QHeaderView.setResizeMode if hasattr(Qt, "_QtCore"): Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR QCoreApplication = Qt._QtCore.QCoreApplication Qt.QtCompat.translate = ( lambda context, sourceText, disambiguation, n: QCoreApplication. translate(context, sourceText, disambiguation, QCoreApplication. CodecForTr, n)) _reassign_misplaced_members("PyQt4") # QFileDialog QtCompat decorator def _standardizeQFileDialog(some_function): """Decorator that makes PyQt4 return conform to other bindings""" def wrapper(*args, **kwargs): ret = (some_function(*args, **kwargs)) # PyQt4 only returns the selected filename, force it to a # standard return of the selected filename, and a empty string # for the selected filter return ret, '' wrapper.__doc__ = some_function.__doc__ wrapper.__name__ = some_function.__name__ return wrapper decorators = { "QFileDialog": { "getOpenFileName": _standardizeQFileDialog, "getOpenFileNames": _standardizeQFileDialog, "getSaveFileName": _standardizeQFileDialog, } } _build_compatibility_members('PyQt4', decorators)
import sys import collections from . import PYQT4 from .QtWidgets import QFileDialog from .py3compat import is_text_string, to_text_string, TEXT_TYPES # ============================================================================= # QVariant conversion utilities # ============================================================================= PYQT_API_1 = False if PYQT4: import sip try: PYQT_API_1 = sip.getapi('QVariant') == 1 # PyQt API #1 except AttributeError: # PyQt <v4.6 PYQT_API_1 = True def to_qvariant(pyobj=None): """Convert Python object to QVariant This is a transitional function from PyQt API #1 (QVariant exist) to PyQt API #2 and Pyside (QVariant does not exist)""" if PYQT_API_1: # PyQt API #1 from PyQt4.QtCore import QVariant return QVariant(pyobj) else: # PyQt API #2 return pyobj
# Alias PyQt-specific functions for PySide compatibility. if hasattr(__QtCore, "pyqtSignal"): Signal = __QtCore.pyqtSignal if hasattr(__QtCore, "pyqtSlot"): Slot = __QtCore.pyqtSlot if hasattr(__QtCore, "pyqtProperty"): Property = __QtCore.pyqtProperty try: __api_version__ = __QtCore.QT_VERSION_STR except AttributeError: pass try: import sip PYQT_QVARIANT_API_1 = sip.getapi('QVariant') < 2 PYQT_QSTRING_API_1 = sip.getapi('QString') < 2 except (ImportError, AttributeError): PYQT_QVARIANT_API_1 = True PYQT_QSTRING_API_1 = True if PYQT_QVARIANT_API_1: to_qvariant = __to_qvariant_1 from_qvariant = __from_qvariant_1 else: __QtCore.QVariant = QVariant = __QVariant_2 to_qvariant = __to_qvariant_2 from_qvariant = __from_qvariant_2 if not PYQT_QSTRING_API_1: __QtCore.QString = QString = __QString_2
# virtual modules that points to the qt module containing these classes QtModel = DelayedModule('QtGui') QtWidgets = DelayedModule('QtGui') QtPrintSupport = DelayedModule('QtGui') if qt_api in (None, 'PyQt4', 'PyQt5'): try: qt_api = qt_api or 'PyQt4' import sip QtCore.qt_slot = QtCore.pyqtSlot QtCore.qt_signal = QtCore.pyqtSignal QtCore.qt_property = QtCore.pyqtProperty # the api version is only available after importing QtCore if qt_api == 'PyQt4': variant_api = sip.getapi('QVariant') string_api = sip.getapi('QString') else: variant_api = 2 string_api = 2 QtModel = DelayedModule('QtCore') QtWidgets = DelayedModule('QtWidgets') QtPrintSupport = DelayedModule('QtPrintSupport') QtQml = DelayedModule('QtQml') QtQuick = DelayedModule('QtQuick') is_deleted = sip.isdeleted except ImportError: qt_api = None elif qt_api in (None, 'PySide'): try:
CONFIGPATH.append('/etc/acq4') # Finally, look for an example config.. CONFIGPATH.extend([ os.path.normpath(os.path.join(modpath, '..', 'config', 'example')), os.path.normpath(os.path.join(modpath, 'config', 'example')), ]) # If we are using PyQt, ACQ4 requires API version 2 for QString and QVariant. # Check for those here.. set_api = True if 'PyQt4' in sys.modules: import sip for api in ['QString', 'QVariant']: try: v = sip.getapi(api) if v != 2: print( "WARNING: ACQ4 requires the use of API version 2 for QString and QVariant, but %s=%s. " "Correct this by calling \"import sip; sip.setapi('QString', 2); sip.setapi('QVariant', 2);\"" " _before_ importing PyQt4." % (api, v)) set_api = False except ValueError: set_api = True elif 'PySide' in sys.modules: set_api = False if set_api: try: import sip sip.setapi('QString', 2)
_getSaveFileName = QtWidgets.QFileDialog.getSaveFileName except ImportError: if _fallback_to_qt4: # fell through, tried PyQt5, failed fall back to PyQt4 QT_API = rcParams['backend.qt4'] QT_RC_MAJOR_VERSION = 4 else: raise # needs to be if so we can re-test the value of QT_API which may # have been changed in the above if block if QT_API in [QT_API_PYQT, QT_API_PYQTv2]: # PyQt4 API from PyQt4 import QtCore, QtGui try: if sip.getapi("QString") > 1: # Use new getSaveFileNameAndFilter() _getSaveFileName = QtGui.QFileDialog.getSaveFileNameAndFilter else: # Use old getSaveFileName() def _getSaveFileName(*args, **kwargs): return (QtGui.QFileDialog.getSaveFileName(*args, **kwargs), None) except (AttributeError, KeyError): # call to getapi() can fail in older versions of sip def _getSaveFileName(*args, **kwargs): return QtGui.QFileDialog.getSaveFileName(*args, **kwargs), None try:
import sip try: sip.getapi('QString') except ValueError: sip.setapi('QString', 2) import PyQt4.Qt Qt = PyQt4.Qt