简体   繁体   中英

Cannot run matplotlib and pyqt4 at the same time

I am running some code using PyQt4, and I would like to plot a figure using its data. But when I try to do that, it will report

QPixmap: Must construct a QGuiApplication before a QPixmap

Below is the code:

from PyQt4 import QtCore
import sys
import matplotlib.pyplot as plt
import numpy as np
def run():
   #here is some code, I delete them since they are useless for this question
   return data1 #data1 is a list with 30 elements

app = QtCore.QCoreApplication(sys.argv)
client.finished.connect(app.quit)
QtCore.QTimer().singleShot(0,lambda:client.timed_range_stream(5000))
app.exec_()
fig = plt.figure()
ax1 = fig.add_subplot(111)
data2 = run()
datalen = np.linspace(0,10,len(data2))
ax1.plot(datalen,data2,lw = 2)
plt.show()

Since the matplotlib is using pyqt4 as backend, I am so confused why this error happened. It should create a QGuiApplication automatically. I mean whether I use pyqt4 before or not, the code below 'app.exec_()' should create a QGuiApplication automatically. Please point out if I am wrong.

Really appreciate your help! Please give me some advice.

The complaint by PyQt is that you are not running a Gui EventLoop. app.exec_() sure starts an event loop, but that depends on what app is. In your case its QCoreApplication object. How do you expect it to start a Gui EventLoop? It's like buying a saucepan and expecting it to cook pizza.

matplotlib is based on PyQt for sure. I'm sure you can use it in console only applications as well. Hence PyQt will not be able to tell if you want a gui or a console app.

QCoreApplication is used when you are writing a console-based application. Fewer events and processes to manage. If you want to show a window, even a simple one, it takes much more work. And the beast to handle that extra work in QGuiApplication

Now to the Qt version. You are using PyQt4 , but the complaint says you need to create a QGuiApplication . However, there is no QGuiApplication or any reference to it in Qt4/PyQt4. This leads me to believe that, your matplotlib copy might be using PyQt5, or PyQt5 dependency comes in from some obscure source, I'm not sure. Check the details of the PyQt version used.

If you are using PyQt4 add from PyQt4 import QtGui in the beginning. Then change the app = QtCore.QCoreApplication(...) to app = QtGui.QApplication(...) .

In case of PyQt5 add from PyQt5 import QtGui, QtWidgets in the beginning. Then change the app = QtCore.QCoreApplication(...) to app = QtWidgets.QApplication(...) .

That'll solve your problem.

PS: Remember, you cannot mix PyQt4 and PyQt5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM