How can you easily select between PyQt or PySide at runtime?

后端 未结 3 1345
长发绾君心
长发绾君心 2021-01-13 06:58

I would like to do something like this in one source file, QT.py:

import sys
import PyQt4

sys.modules[\"Qt\"] = PyQt4

Then import this fil

3条回答
  •  生来不讨喜
    2021-01-13 07:04

    update: Figured out method more in line with your requirements:

    You can structure your pseudo-module as:

    Qt/
    Qt/__init__.py
    Qt/QtCore/__init__.py
    Qt/QtGui/__init__.py
    

    Where Qt/__init__.py is:

    import QtCore, QtGui
    

    Qt/QtCore/__init__.py is:

    from PyQt4.QtCore import *
    

    Qt/QtGui/__init__.py is:

    from PyQt4.QtGui import *
    

    Then, in your code, you can reference it as follows:

    import sys
    from Qt import QtGui
    app = QtGui.QApplication(sys.argv)
    
    from Qt.QtGui import *
    
    window = QWidget()
    window.show()
    
    app.exec_()
    

    I highly recommend against using from Qt.QtGui import * in your code as importing everything is considered bad form in Python since you lose all namespaces in the process.

    update: I like Ryan's suggestion of conditional imports. I'd recommend combining that into the above code. For example:

    Qt/QtGui/__init__.py:

    import sys
    if '--PyQt4' in sys.argv:
        from PyQt4.QtGui import *
    else:
        from PySide.QtGui import *
    

提交回复
热议问题