Python Forum

Full Version: I build and install PyQT for python2 but it not recognize in python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I try to run Spyder on python 2 therefore I needed to build PyQT.

make and make install for PyQT5, sip work without errors but spyder still complain that PyQT not instaled
also when I run python and the run "import PyQT5" it complain: ImportError: No module named PyQT5
I also install pip install PyQT5 and it not helped.

Thanks
Please show your code, how do you import PyQt5? (not PyQT5)

for example

from PyQt5.QtWidgets import (QWidget, QLabel, QComboBox, QPushButton,
                             QHBoxLayout, QVBoxLayout,
                             QPlainTextEdit, QApplication, QSlider)
from PyQt5.QtGui import (QIcon, QCursor)
Import PyQt5 works but:
Output:
$ python Python 2.7.15+ (default, Oct 2 2018, 22:12:08) [GCC 8.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import PyQt5 >>> from PyQt5.QtWidgets import (QWidget, QLabel, QComboBox, QPushButton, ... QHBoxLayout, QVBoxLayout, ... QPlainTextEdit, QApplication, QSlider) Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named sip >>> from PyQt5.QtGui import (QIcon, QCursor) Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named sip >>> import sip >>> from PyQt5.QtWidgets import (QWidget, QLabel, QComboBox, QPushButton, ... QHBoxLayout, QVBoxLayout, ... QPlainTextEdit, QApplication, QSlider) Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name QWidget >>> from PyQt5.QtGui import (QIcon, QCursor) Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name QIcon >>> import QIcon Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named QIcon
Maybe there are still many mistakes in the code or in your PyQt5 Installation?

here'e a simple PyQt5 example, does this work for you?

#!/usr/bin/python3
# -*- coding: utf-8 -*-
#############################################################################

from PyQt5.QtCore import (QFile, QFileInfo, QPoint, QRect, QSettings, QSize,
		Qt, QTextStream)
from PyQt5.QtGui import QIcon, QKeySequence
from PyQt5.QtWidgets import (QAction, QApplication, QFileDialog, QMainWindow,
		QMessageBox, QTextEdit)

class MainWindow(QMainWindow):
	def __init__(self):
		super(MainWindow, self).__init__()

		self.curFile = ''

		self.textEdit = QTextEdit()
		self.setCentralWidget(self.textEdit)

		self.createActions()
		self.createMenus()
		self.createToolBars()
		self.createStatusBar()

		self.readSettings()

		self.textEdit.document().contentsChanged.connect(self.documentWasModified)

		self.setCurrentFile('')

	def closeEvent(self, event):
		if self.maybeSave():
			self.writeSettings()
			event.accept()
		else:
			event.ignore()

	def newFile(self):
		if self.maybeSave():
			self.textEdit.clear()
			self.setCurrentFile('')

	def open(self):
		if self.maybeSave():
			fileName, _ = QFileDialog.getOpenFileName(self)
			if fileName:
				self.loadFile(fileName)

	def save(self):
		if self.curFile:
			return self.saveFile(self.curFile)

		return self.saveAs()

	def saveAs(self):
		fileName, _ = QFileDialog.getSaveFileName(self)
		if fileName:
			return self.saveFile(fileName)

		return False

	def about(self):
		QMessageBox.about(self, "About Application",
				"The <b>Application</b> example demonstrates how to write "
				"modern GUI applications using Qt, with a menu bar, "
				"toolbars, and a status bar.")

	def documentWasModified(self):
		self.setWindowModified(self.textEdit.document().isModified())

	def createActions(self):
		root = QFileInfo(__file__).absolutePath()

		self.newAct = QAction(QIcon.fromTheme('gtk-new'), "&New", self,
				shortcut=QKeySequence.New, statusTip="Create a new file",
				triggered=self.newFile)

		self.openAct = QAction(QIcon.fromTheme('gtk-open'), "&Open...",
				self, shortcut=QKeySequence.Open,
				statusTip="Open an existing file", triggered=self.open)

		self.saveAct = QAction(QIcon.fromTheme('gtk-save'), "&Save", self,
				shortcut=QKeySequence.Save,
				statusTip="Save the document to disk", triggered=self.save)

		self.saveAsAct = QAction(QIcon.fromTheme('gtk-save-as'),"Save &As...", self,
				shortcut=QKeySequence.SaveAs,
				statusTip="Save the document under a new name",
				triggered=self.saveAs)

		self.exitAct = QAction(QIcon.fromTheme('application-exit'),"E&xit", self, shortcut="Ctrl+Q",
				statusTip="Exit the application", triggered=self.close)

		self.cutAct = QAction(QIcon.fromTheme('edit-cut'), "Cu&t", self,
				shortcut=QKeySequence.Cut,
				statusTip="Cut the current selection's contents to the clipboard",
				triggered=self.textEdit.cut)

		self.copyAct = QAction(QIcon.fromTheme('edit-copy'), "&Copy", self,
				shortcut=QKeySequence.Copy,
				statusTip="Copy the current selection's contents to the clipboard",
				triggered=self.textEdit.copy)

		self.pasteAct = QAction(QIcon.fromTheme('edit-paste'), "&Paste",
				self, shortcut=QKeySequence.Paste,
				statusTip="Paste the clipboard's contents into the current selection",
				triggered=self.textEdit.paste)

		self.aboutAct = QAction(QIcon.fromTheme('help-info'),"&About", self,
				statusTip="Show the application's About box",
				triggered=self.about)

		self.aboutQtAct = QAction(QIcon.fromTheme('help-about'),"About &Qt", self,
				statusTip="Show the Qt library's About box",
				triggered=QApplication.instance().aboutQt)

		self.cutAct.setEnabled(False)
		self.copyAct.setEnabled(False)
		self.textEdit.copyAvailable.connect(self.cutAct.setEnabled)
		self.textEdit.copyAvailable.connect(self.copyAct.setEnabled)

	def createMenus(self):
		self.fileMenu = self.menuBar().addMenu("&File")
		self.fileMenu.addAction(self.newAct)
		self.fileMenu.addAction(self.openAct)
		self.fileMenu.addAction(self.saveAct)
		self.fileMenu.addAction(self.saveAsAct)
		self.fileMenu.addSeparator();
		self.fileMenu.addAction(self.exitAct)

		self.editMenu = self.menuBar().addMenu("&Edit")
		self.editMenu.addAction(self.cutAct)
		self.editMenu.addAction(self.copyAct)
		self.editMenu.addAction(self.pasteAct)

		self.menuBar().addSeparator()

		self.helpMenu = self.menuBar().addMenu("&Help")
		self.helpMenu.addAction(self.aboutAct)
		self.helpMenu.addAction(self.aboutQtAct)

	def createToolBars(self):
		self.fileToolBar = self.addToolBar("File")
		self.fileToolBar.addAction(self.newAct)
		self.fileToolBar.addAction(self.openAct)
		self.fileToolBar.addAction(self.saveAct)

		self.editToolBar = self.addToolBar("Edit")
		self.editToolBar.addAction(self.cutAct)
		self.editToolBar.addAction(self.copyAct)
		self.editToolBar.addAction(self.pasteAct)

	def createStatusBar(self):
		self.statusBar().showMessage("Ready")

	def readSettings(self):
		settings = QSettings("Trolltech", "Application Example")
		pos = settings.value("pos", QPoint(200, 200))
		size = settings.value("size", QSize(400, 400))
		self.resize(size)
		self.move(pos)

	def writeSettings(self):
		settings = QSettings("Trolltech", "Application Example")
		settings.setValue("pos", self.pos())
		settings.setValue("size", self.size())

	def maybeSave(self):
		if self.textEdit.document().isModified():
			ret = QMessageBox.warning(self, "Application",
					"The document has been modified.\nDo you want to save "
					"your changes?",
					QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

			if ret == QMessageBox.Save:
				return self.save()

			if ret == QMessageBox.Cancel:
				return False

		return True

	def loadFile(self, fileName):
		file = QFile(fileName)
		if not file.open(QFile.ReadOnly | QFile.Text):
			QMessageBox.warning(self, "Application",
					"Cannot read file %s:\n%s." % (fileName, file.errorString()))
			return

		inf = QTextStream(file)
		QApplication.setOverrideCursor(Qt.WaitCursor)
		self.textEdit.setPlainText(inf.readAll())
		QApplication.restoreOverrideCursor()

		self.setCurrentFile(fileName)
		self.statusBar().showMessage("File loaded", 2000)

	def saveFile(self, fileName):
		file = QFile(fileName)
		if not file.open(QFile.WriteOnly | QFile.Text):
			QMessageBox.warning(self, "Application",
					"Cannot write file %s:\n%s." % (fileName, file.errorString()))
			return False

		outf = QTextStream(file)
		QApplication.setOverrideCursor(Qt.WaitCursor)
		outf << self.textEdit.toPlainText()
		QApplication.restoreOverrideCursor()

		self.setCurrentFile(fileName);
		self.statusBar().showMessage("File saved", 2000)
		return True

	def setCurrentFile(self, fileName):
		self.curFile = fileName
		self.textEdit.document().setModified(False)
		self.setWindowModified(False)

		if self.curFile:
			shownName = self.strippedName(self.curFile)
		else:
			shownName = 'untitled.txt'

		self.setWindowTitle("%s[*] - Application" % shownName)

	def strippedName(self, fullFileName):
		return QFileInfo(fullFileName).fileName()


if __name__ == '__main__':

	import sys

	app = QApplication(sys.argv)
	mainWin = MainWindow()
	mainWin.show()
	sys.exit(app.exec_())
running the example code result:
Output:
$ python testqt.py Traceback (most recent call last): File "testqt.py", line 5, in <module> from PyQt5.QtCore import (QFile, QFileInfo, QPoint, QRect, QSettings, QSize, ImportError: No module named sip
I added import sip in the code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#############################################################################

import sip
from PyQt5.QtCore import (QFile, QFileInfo, QPoint, QRect, QSettings, QSize,
        Qt, QTextStream)
from PyQt5.QtGui import QIcon, QKeySequence
from PyQt5.QtWidgets import (QAction, QApplication, QFileDialog, QMainWindow,
        QMessageBox, QTextEdit)
But got the same error.

I install PySide2 with pip and run its example test:
import sys
from PySide2.QtWidgets import QApplication, QLabel

if __name__ == "__main__":
    app = QApplication(sys.argv)
    label = QLabel("Hello World")
    label.show()
    sys.exit(app.exec_())
and It works and window with Hello World appear.
Spyder still failed.

I run it with pdb:
Output:
python -m pdb /home/osboxes/.virtualenvs/myenv_env/bin/spyder > /home/osboxes/.virtualenvs/myenv_env/bin/spyder(4)<module>() -> import re (Pdb) break /home/osboxes/.virtualenvs/myenv_env/local/lib/python2.7/site-packages/qtpy/__init__.py:155 Breakpoint 1 at /home/osboxes/.virtualenvs/myenv_env/local/lib/python2.7/site-packages/qtpy/__init__.py:155 (Pdb) c > /home/osboxes/.virtualenvs/myenv_env/local/lib/python2.7/site-packages/qtpy/__init__.py(155)<module>() -> from PySide2 import __version__ as PYSIDE_VERSION # analysis:ignore (Pdb) n > /home/osboxes/.virtualenvs/myenv_env/local/lib/python2.7/site-packages/qtpy/__init__.py(156)<module>() -> from PySide2.QtCore import __version__ as QT_VERSION # analysis:ignore (Pdb) n ImportError: "/usr/lib/x86_64-linux-gnu/libQt5Core.so.5: version `Qt_5.12' not found (required by /home/osboxes/.virtualenvs/myenv_env/local/lib/python2.7/site-packages/PySide2/QtCore.so)" > /home/osboxes/.virtualenvs/myenv_env/local/lib/python2.7/site-packages/qtpy/__init__.py(156)<module>() -> from PySide2.QtCore import __version__ as QT_VERSION # analysis:ignore
But when I run from a test file or interactive python the following code, it not return an error:
from PySide2 import __version__ as PYSIDE_VERSION  # analysis:ignore
from PySide2.QtCore import __version__ as QT_VERSION  # analysis:ignore
(Mar-28-2019, 12:49 PM)nadavvin Wrote: [ -> ]I also install pip install PyQT5 and it not helped.

I think pip installs PyQt5 for python3.
But I install with python2:
Output:
$ pip install PyQt5 Requirement already satisfied: PyQt5 in /home/osboxes/.virtualenvs/myenv_env/lib/python2.7/site-packages (5.12.1)
maybe you can try for python 2

sudo apt install python-pyqt5