我无法使用PySide2和.ui文件来使PyQtGraph正常工作,我在其中将QWidget提升为Qt-Designer中的PlotWidget。当我使用PyQt5时,它工作正常,但是使用PySide2,我得到以下消息:
Qt WebEngine seems to be initialized from a plugin. Please set Qt::AA_ShareOpenGLContexts using >QCoreApplication::setAttribute before constructing QGuiApplication.
"QFormBuilder was unable to create a custom widget of the class 'PlotWidget'; defaulting to base class 'QWidget'."
Traceback (most recent call last):
File "test_widget3.py", line 13, in <module>
window.graphWidget.plot([1,5,10], [1,2,7])
AttributeError: 'PySide2.QtWidgets.QWidget' object has no attribute 'plot'
代码:
import sys
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtUiTools import QUiLoader
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
app = QtWidgets.QApplication(sys.argv)
loader = QUiLoader()
window = loader.load("pyqtgraph_window.ui")
window.graphWidget.plot([1,5,10], [1,2,7])
window.show()
app.exec_()
使用PyQt5(有效):
import sys
from PyQt5 import QtWidgets, uic
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
app = QtWidgets.QApplication(sys.argv)
window = uic.loadUi("pyqtgraph_window.ui")
window.graphWidget.plot([1,5,10], [1,2,7])
window.show()
app.exec_()
。ui:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="PlotWidget" name="graphWidget" native="true"/>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<customwidgets>
<customwidget>
<class>PlotWidget</class>
<extends>QWidget</extends>
<header>pyqtgraph</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
我使用来自Github和PySide2 v5.12的PyQtGraph的最新开发版本谢谢您的帮助!
loadUi使用名称动态访问类,该概念在C ++中不存在,因此QUiLoader具有此限制,因此解决方案是指示转换显式覆盖createWidget方法:
import os
import sys
from PySide2 import QtCore, QtGui, QtWidgets, QtUiTools
import pyqtgraph as pg
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class UiLoader(QtUiTools.QUiLoader):
def createWidget(self, className, parent=None, name=""):
if className == "PlotWidget":
return pg.PlotWidget(parent=parent)
return super().createWidget(className, parent, name)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
loader = UiLoader()
window = loader.load(os.path.join(CURRENT_DIR, "pyqtgraph_window.ui"))
window.graphWidget.plot([1, 5, 10], [1, 2, 7])
window.show()
sys.exit(app.exec_())