PySide2 与 Pyqt5 的区别

参考:Differences Between PySide and PyQt/zh & PyQt5 vs PySide2: What's the difference between the two Python Qt libraries?

API 差异

PySide 只支持 PyQt 的 API 2(详见 PSEP 101) 。新的 API 2 提供了 Qt 类和 python 原生数据类型之间的自动转换,这样本质上也更 Pythonic。

1 UI 文件

PyQt5 这样写:

import sys
from PyQt5 import QtWidgets, uic

app = QtWidgets.QApplication(sys.argv)

window = uic.loadUi("mainwindow.ui")
window.show()
app.exec()

PySide2 这样写:

import sys
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtUiTools import QUiLoader

loader = QUiLoader()

app = QtWidgets.QApplication(sys.argv)
window = loader.load("mainwindow.ui", None)
window.show()
app.exec_()

为了载入 UI 到 PyQt5 对象,例如 QMainWindow.__init__ 之中,您可以调用 uic.loadUI 函数并传入 self 参数,即:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import uic


class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        uic.loadUi("mainwindow.ui", self)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

而 PySide2 不支持这种以 self 作为第二个参数的方式。如果您想要令 PySide2 实现上述功能,可以这样:

import sys
from PySide2 import QtWidgets
from PySide2.QtUiTools import QUiLoader

loader = QUiLoader()

def mainwindow_setup(w):
    w.setTitle("MainWindow Title")

app = QtWidgets.QApplication(sys.argv)

window = loader.load("mainwindow.ui", None)
mainwindow_setup(window)
window.show()
app.exec()

2 转换 UI 文件为 Python 文件

PyQt5:

pyuic5 mainwindow.ui -o MainWindow.py

而 PySide2:

pyside2-uic mainwindow.ui -o MainWindow.py

在调用的时候:

PyQt5:

import sys
from PyQt5 import QtWidgets
from MainWindow import Ui_MainWindow

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setupUi(self)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

而 PySide2:

import sys
from PySide2 import QtWidgets
from MainWindow import Ui_MainWindow

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setupUi(self)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

3 Slots and Signals

PyQt5 使用 pyqtSignalpyqtSlot,而 PySide2 使用 SignalSlot 自定义信号与槽。

my_custom_signal = pyqtSignal()  # PyQt5
my_custom_signal = Signal()  # PySide2

my_other_signal = pyqtSignal(int)  # PyQt5
my_other_signal = Signal(int)  # PySide2

或者

@pyqtslot
def my_custom_slot():
    pass

@Slot
def my_custom_slot():
    pass

为了统一,可以定义 qt.py 文件:

try:
    # PySide2
    from PySide2 import QtGui, QtWidgets, QtCore
    from PySide2.QtCore import Signal, Slot
except ImportError:
    # PyQt5
    from PyQt5 import QtGui, QtWidgets, QtCore
    from PyQt5.QtCore import pyqtSignal as Signal, pyqtSlot as Slot

其他文件调用时:

from .qt import QtGui, QtWidgets, QtCore

你可能感兴趣的:(PySide2 与 Pyqt5 的区别)