I am learning PyQt4 and have written a simple expression evaluator. I am having difficulty debugging the second to last line of my init function (self.connect..... ). Python returns 'syntax error' but I can't spot the problem. I'd appreciate any help you can offer pointing it out. I am using Python 2.7.6 on Ubuntu 13.10 Linux 64 bit. I am aware that the whitespace formatting is slightly off which is an artifact of my cutting and pasting but the code IS EXACTLY as I am running it otherwise.
<pre> <code>
from __future__ import division
import sys
from math import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(tparent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an epression and press enter")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit(self.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"),self.updateUi)
self.setWindowTitle("Calculate")
def updateUI(self):
try:
text = unicode(self.lineedit.text())
self.browser.append("%s = <b>%s</b>" % (text, eval(text)))
except:
self.browser.append("<font color=red>%s is invalid!</font>" % text)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
You're missing a close paren from the line above
self.lineedit(self.setFocus())
self.connect(self.lineedit, SIGNAL("returnPressed()"),self.updateUi)
Related
I am trying to implement in my project a QListWidget with the possibility of moving elements by drag and drop
I try to integrate it into the project in the simplest way without success, while outside I have no problem executing it.
EDIT:The problem seems to come from the realsense library, without its, DAD works
Here is its implementation:
priorityContainer.py:
class priorityContainer(QListWidget):
def __init__(self):
super().__init__()
self.setIconSize(QSize(124, 124))
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDefaultDropAction(Qt.MoveAction)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
self.setDragEnabled(True)
for i in range(5):
QListWidgetItem( 'Item '+str(i), self)
main_interface.py:
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
import traceback, sys, os
import pyrealsense2 as rs
from ressource.interface import priorityContainer
class UI_main(QMainWindow):
def __init__(self):
super(UI_main, self).__init__()
self.setupUi()
self.show()
def setupUi(self):
self.centralwidget = QWidget(self)
self.mainVcontainer = QVBoxLayout(self.centralwidget)
self.listWidget = priorityContainer.priorityContainer()
self.mainVcontainer.addWidget(self.listWidget)
self.setCentralWidget(self.centralwidget)
def root_path(self):
return os.path.abspath(os.sep)
if __name__ == "__main__":
app = QApplication(sys.argv)
ui = UI_main()
sys.exit(app.exec_())
I have solved my problem by adding these lines before any other imports where I import my pyrealsense2 librairies:
import sys
sys.coinit_flags = 2
import pythoncom
Reference to the fix: https://github.com/IntelRealSense/librealsense/issues/6174
I'm writing a program using
Linux Mint 19
Python version: 3.6.6
Qt version: 5.9.5
PyQt version: 5.10.1
SIP version: 4.19.7
and I have just noticed that the standard short key for closing (CTRL+W) has stopped working.
In my file I've written the following line to connect it to the close button
self.closeBtn.setShortcut(QtGui.QKeySequence(QtGui.QKeySequence.Close))
But nothing happens if I push the buttons. If I change it to
self.closeBtn.setShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_W))
it works as intended.
I've also tried with
self.closeBtn.setShortcut(QtGui.QKeySequence(QtGui.QKeySequence.Quit))
But CTRL+Q does nothing either. The standard keys work for other applications.
Any ideas on why that could be?
enum QKeySequence::StandardKey
This enum represent standard key bindings.
They can be used to assign platform dependent keyboard shortcuts to a QAction.
http://doc.qt.io/qt-5/qkeysequence.html#StandardKey-enum
Try it:
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class MyButton(QMainWindow):
def __init__(self,parent=None):
super().__init__(parent)
btn1 = QPushButton("Click or `Ctrl+Q`", clicked=self.close)
btn1.setShortcut(QKeySequence("Ctrl+Q"))
btn2 = QPushButton("QKeySequence.Close",
clicked=lambda: print("\n Please Press -> Ctrl+W"))
quitAct = QAction("Close", btn2, triggered=self.close)
quitAct.setShortcuts(QKeySequence.Close) # <<<=======
btn2.addAction(quitAct)
btn3 = QPushButton("Click or `Ctrl+P`", clicked=lambda: print("Hello Kajsa"))
btn3.setShortcut(QKeySequence("Ctrl+P"))
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
v_layout = QVBoxLayout(centralWidget)
v_layout.addWidget(btn1)
v_layout.addWidget(btn2)
v_layout.addWidget(btn3)
if __name__ == '__main__':
app=QApplication([])
mb = MyButton()
mb.show()
app.exec_()
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class demo_widget(QWidget):
def __init__(self,parent=None):
super().__init__(parent)
lay_content = QVBoxLayout()
self.closeBtn = QPushButton("Close")
self.lineEdit = QLineEdit()
self.closeBtn.clicked.connect(self.slt_close)
self.closeAction = QAction(self, triggered=self.slt_close)
self.closeAction.setShortcuts([QKeySequence("Ctrl+Q"), QKeySequence("Ctrl+W")])
self.closeBtn.addAction(self.closeAction)
lay_content.addWidget(self.closeBtn)
lay_content.addWidget(self.lineEdit)
self.setLayout(lay_content)
def slt_close(self):
self.lineEdit.setText("close")
if __name__ == '__main__':
app=QApplication([])
demo = demo_widget()
demo.show()
app.exec_()
I'm doing some simple PySide on 3Dsmax 2015.
This is my error:
python.ExecuteFile "C:\Program Files\Autodesk\3ds Max 2015\scripts\Python\demoUniTest.py"
-- Runtime error: Line 32 <module>()
<type 'exceptions.RuntimeError'> A QApplication instance already exists.
This is my code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from math import *
class Form(QDialog):
def __init__(self,parent=None):
super(Form,self).__init__(parent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an expression and press Enter")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"),self.updateUi)
self.setWindowTitle("Calculate")
def updateUi(self):
try:
text = self.lineedit.text()
self.browser.append("%s = <b>%s</b>" % (text,eval(text)))
except:
self.browser.append("<font color=red>%s is invalid</font>" %text)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
When I use this code on Pycharm,I don't get any errors. It only appears when I use it on 3Dsmax 2015 Listener
Direct citation from the helpfile (Using PySide):
Normally one creates a PySide application object in a script using
QtGui.QApplication(). However, in 3ds Max, there is already a PySide
application running, so you get a handle for that object like this:
QtGui.QApplication.instance()
As a note this has changed somewhat in 3DS Max 2018 and PySide2. I'm just playing around with it myself right now and I was able to get it working after a bit of tinkering. Here's a link to the documentation, though be warned that there is a small typo in the code (at least at the time of writing): http://help.autodesk.com/view/3DSMAX/2018/ENU/?guid=__developer_what_s_new_in_3ds_max_python_api_what_s_new_in_the_3ds_max_2018_p_html
As mentioned in other answers you need to make your UI a child of the main 3DS Max application. The good news is that they have simplified this a bit for you with the function GetQMaxMainWindow(). Use it like this:
from PySide2 import QtWidgets, QtCore, QtGui
import MaxPlus
import os
class SampleUI(QtWidgets.QDialog):
def __init__(self, parent=MaxPlus.GetQMaxMainWindow()):
super(SampleUI, self).__init__(parent)
self.initUI()
def initUI(self):
mainLayout = QtWidgets.QHBoxLayout()
testBtn = QtWidgets.QPushButton("Test!")
mainLayout.addWidget(testBtn)
self.setLayout(mainLayout)
if __name__ == "__main__":
try:
ui.close()
except:
pass
ui = SampleUI()
ui.show()
You're creating an instance of QApplication in the line:
app = QApplication(sys.argv)
And getting that error because there's another instance of QApplication created somewhere before that (presumably somewhere in "3Dsmax 2015 Listener") and you're only allowed one.
See:
QT documentation on QApplication
I have written the following python pyQT code to run a simple dialog application. However that does not work.
I'm using PyQT 5.0 on Win 8 64BIT.
It simply does not work and no error is returned.
When I run it, the current IDE (which is pycharm) gets blurred (which happens when a new windows is shown generally), though, no window is shown, and when I stop the execution, it returns -1. Here is my code:
from __future__ *
from sys import *
from math import *
from PyQT5.QtCore import *
from PyQT5.QtGui import *
from PyQT5.QtWidgets import *
class Form (QGuiDialog) :
def __init__(self, parent=None) :
super(Form, self).__init__(parent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an Expression, then Press Enter")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateGui)
self.setWindowTitle("Calculate")
def updateGui (self) :
try :
text = unicode(self.lineedit.txt())
self.browser.append("%s = <b>%s<b>" % (text, eval(text)))
except :
self.browser.append("%s is an invalid expression" % (text))
app = QCoreApplication(sys.agrv)
x = Form()
x.show()
app.exec_()
It is my understanding that PyQT5 does not support SIGNALs and SLOTS used in PyQT4.
Therefore I think you might try a different way instead of SIGNAL for your lineedit.
Instead of:
self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateGui)
try
self.lineedit.textChanged.connect(self.updateGui)
Also I would suggest reading here the differences between PyQT5 and PyQT4 http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html
and check in the PyQT5 folder on your drive for extremely useful samples.
You have several problems in your code, I will address just some of them:
In order to actually see something with Qt you need to create a QApplication not a QCoreApplication.
You must fix the imports in the the line: from __future__ *.
On updateGui you need to initialize text if you want the exception handler to work fine.
Finally this is a working example of your code:
NOTE: I don't have PyQt5 just PyQt4, but I'm sure you'll get the idea ;)
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form (QDialog) :
def __init__(self, parent=None) :
super(Form, self).__init__(parent)
self.browser = QTextBrowser()
self.lineedit = QLineEdit("Type an Expression, then Press Enter")
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateGui)
self.setWindowTitle("Calculate")
def updateGui(self):
text = self.lineedit.text()
self.lineedit.clear()
try :
text = unicode(text)
self.browser.append("%s = <b>%s<b>" % (text, eval(text)))
except :
self.browser.append("<font color=red>%s</font> is an invalid expression" % (text))
app = QApplication(sys.argv)
x = Form()
x.show()
app.exec_()
I managed to create and thread a PyQt application to do some screenshots of a list of urls. It's working really good, but it's always crashing on some websites (or at least on for sure).
Softpedia.com is one of them. It's just crashing Python with a segmentation fault just before the loadFinished event. Even if I don't use my threaded application but "raw" PyQt.
I tested with basic PyQt based browser I found on the web and I got the same issue.
Does anybody have an idea? I'm starting to think that this may be a dead end, which is not really a good news.
Thank you all!
There's probably some kind of issue with the the code you are using, this code shouldn't raise errors:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui, QtWebKit
class MyWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.barProgress = QtGui.QProgressBar(self)
self.barProgress.setFixedSize(80, 15)
self.barProgress.setVisible(False)
self.barStatus = QtGui.QStatusBar(self)
self.barStatus.addPermanentWidget(self.barProgress)
self.webView = QtWebKit.QWebView(self)
settingsWeb = [
QtWebKit.QWebSettings.PluginsEnabled
]
for setting in settingsWeb:
self.webView.settings().setAttribute(setting, True)
self.setStatusBar(self.barStatus)
self.setCentralWidget(self.webView)
self.webView.loadFinished.connect(self.on_webView_loadFinished)
self.webView.loadFinished.connect(self.barProgress.hide)
self.webView.loadStarted.connect(self.barProgress.show)
self.webView.loadProgress.connect(self.barProgress.setValue)
#QtCore.pyqtSlot()
def on_webView_loadFinished(self):
QtGui.QMessageBox.information(None, "Info", "Load finished!")
def loadUrl(self, url):
self.webView.load(QtCore.QUrl(url))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
main.loadUrl("http://www.example.com/")
sys.exit(app.exec_())