如何在运行时轻松地在 PyQt 或 PySide 之间进行选择? [英] How can you easily select between PyQt or PySide at runtime?

查看:45
本文介绍了如何在运行时轻松地在 PyQt 或 PySide 之间进行选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个源文件 QT.py 中做这样的事情:

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 file in the other source files, and use it like this:

import QT
from Qt.QtCore import *

因此我可以在 QT.py 中从 PyQt4 更改为 PySide,而无需触及所有源文件(使用可能很难看的 sed 脚本)这些模块大多是 API 兼容的,我想对它们都进行测试.是否有捷径可寻?(因为我尝试的方法不起作用)

So I can change from PyQt4 to PySide in QT.py without touching all the source files (with a possibly ugly sed script) These modules are mostly API compatibile and I would like to test them both. Is there an easy way to do this? (Because the ways I tried are not working)

也许我需要 imp 模块,但它似乎太低级了.

Maybe the I need imp module, but it seems too low level.

有什么想法吗?

推荐答案

更新:找到更符合你要求的方法:

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

Qt/__init__.py 在哪里:

import QtCore, QtGui

Qt/QtCore/__init__.py 是:

from PyQt4.QtCore import *

Qt/QtGui/__init__.py 是:

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_()

强烈建议不要在你的代码中使用 from Qt.QtGui import * 因为 import everything 在 Python 中被认为是不好的形式,因为你输了进程中的所有命名空间.

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.

更新:我喜欢 Ryan 的有条件导入的建议.我建议将其合并到上面的代码中.例如:

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 *

这篇关于如何在运行时轻松地在 PyQt 或 PySide 之间进行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆