Where is the error coming from? - pyqt

I'm getting this error but I don't have any idea what I'm doing wrong:
>>> runfile('C:/Users/218003107/callphreeqcInput.pyw', wdir=r'C:/Users/218003107')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\218003107\AppData\Local\Continuum\Anaconda\lib\site-
packages\spyderlib\widgets\externalshell\sitecustomize.py", line 580, in runfile
execfile(filename, namespace)
File "C:/Users/218003107/callphreeqcInput.pyw", line 5, in <module>
class MyForm(QtGui.QMainWindow, phreqMDI.Ui_MainWindow):
NameError: name 'phreqMDI' is not defined
>>>"
I'm running this code:
import sys
from PyQt4 import QtCore, QtGui
from phreqMDI import *
class MyForm(QtGui.QMainWindow, phreqMDI.Ui_MainWindow):
def __init__(self, parent=None):
super(MyForm,self).__init__(parent)
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
self.connect(wt1,SIGNAL('textChanged()'),wtResult)
self.connect(wt2,SIGNAL('textChanged()'),wtResult)
self.connect(wt3,SIGNAL('textChanged()'),wtResult)
self.connect(wt4,SIGNAL('textChanged()'),wtResult)
def wtResult(self):
if len(self.ui.wt1.text())!=0:
a=float(self.ui.wt1.text())
else:
a=0
if len(self.ui.wt2.text())!=0:
b=float(self.ui.wt2.text())
else:
b=0
if len(self.ui.wt3.text())!=0:
c=float(self.ui.wt3.text())
else:
c=0
if len(self.ui.wt4.text())!=0:
c=float(self.ui.wt4.text())
else:
d=0
sum=a+b+c+d
self.ui.wt_total.setText(str(sum))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
=MyForm()
myapp.show()
app.exec_()
Here are the first few lines (not showing all 500 lines) of the ui file that created using Qt Designer and converted to .py with pyuic4 (which went fine):
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 677)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
What am I doing wrong here ?

Since you've imported all from phreqMDI, code should be:
from phreqMDI import *
class MyForm(QtGui.QMainWindow, Ui_MainWindow):
or
import phreqMDI
class MyForm(QtGui.QMainWindow, phreqMDI.Ui_MainWindow):

Related

pyqt keypress event in lineedit

i have created a untitled ui where exists one lineedit.
now i want to get the value of whatever i type in lineedit immediately
i figured out it could be done using keypressevent but i exactly didn't understand how to use it in lineedit now
from untitled import *
from PyQt4 import QtGui # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MainWindow(QMainWindow, Ui_Dialog):
def event(self, event):
if type(event) == QtGui.QKeyEvent:
print (event.key())
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
#here i want to get what is keypressed in my lineEdit
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
this is my untitled.py code that i have imported
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(662, 207)
self.lineEdit = QtGui.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(50, 30, 113, 27))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
If you want to get the whole text in the line-edit as it is entered, you can use the textEdited signal. However, if you just want to get the current key that was pressed, you can use an event-filter.
Here is how to use both of these approaches:
class MainWindow(QMainWindow, Ui_Dialog):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.lineEdit.installEventFilter(self)
self.lineEdit.textEdited.connect(self.showCurrentText)
def eventFilter(self, source, event):
if (event.type() == QEvent.KeyPress and
source is self.lineEdit):
print('key press:', (event.key(), event.text()))
return super(MainWindow, self).eventFilter(source, event)
def showCurrentText(self, text):
print('current-text:', text)

PYQT4 not able to write into excelwriter

I have a gui I created in pyqt4 that has a function to call a module that is supposed to write into an excel sheet using pandas excelwriter. For some reason, it creates the worksheet but does not write anything into it. It just crashes my qui without any errors..when I run it in debug mode, it apparently goes through without any issues. I have been debugging this for the past few days and now point the issue between pyqt and excelwriter.Is there a known issue that pyqt does not like pandas excelwriter?
from PyQt4 import QtCore,QtGui
import sys
from MAIN_GUI import *
if __name__=="__main__":
app = Qt.Gui.QApplication(sys.argv)
class MAIN_GUI(QtGui.QMainWindow):
def __init__self:
super(MAIN_GUI, self.__init__:
self.uiM=Ui_MainWindow
self.uiM.setupUi(self)
self.connect(self.uiM.updateALL_Button,QtCore.SIGNAL('clicked()'),self.updateALLEXCEL)
def updateALLEXCEL(self):
import excel_dummy
main_gui = MAIN_GUI()
main_gui.show()
main_gui.raise_()
sys.exit(app.exec_())
---excel_dummy.py---
import pandas as pd
from pandas import ExcelWriter
def excelify():
with ExcelWriter('/home/Desktop/Excelified/final.xlsx', engine='xlsxwriter') as writer:
workbook=writer.book
worksheet=workbook.add_worksheet()
worksheet.write(2,2,'just write something')
writer.save()
excelify()
---MAIN_GUI.py---
from PyQt4 import QtCore,QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.unicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(320,201)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.updateALL_Button = QtGui.QPushButton(self.centralwidget)
self.updateALL_Button.setGeometry(QtCore.QRect(40,110,161,27))
self.updateALL_Button.setFocusPolicy(QtCore.Qt.NoFocus)
self.updateAll_Button.setObjectName(_fromUtf8("Options_updateALL_Button"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 320, 24))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self,MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.updateALL_Button.setText(_translate("MainWindow", "updateALL", None))
The code below works for me. That is, after I click the updateALL button, it prints this:
file size: 5259 "/tmp/final.xlsx"
and viewing the resulting file shows this:
Note that I had to fix quite a lot of bugs to get your example to work. So make sure you use all the files below when you test it:
main.py:
import sys
from MAIN_GUI import *
from PyQt4 import QtGui, QtCore
if __name__=="__main__":
app = QtGui.QApplication(sys.argv)
class MAIN_GUI(QtGui.QMainWindow):
def __init__(self):
super(MAIN_GUI, self).__init__()
self.uiM = Ui_MainWindow()
self.uiM.setupUi(self)
self.connect(self.uiM.updateALL_Button,QtCore.SIGNAL('clicked()'),self.updateALLEXCEL)
def updateALLEXCEL(self):
try:
import excel_dummy
except:
from traceback import format_exception
msg = ''.join(format_exception(*sys.exc_info()))
mb = QtGui.QMessageBox()
mb.setWindowTitle('Error')
mb.setText('Click Show Details to get the Traceback')
mb.setDetailedText(msg)
mb.exec_()
main_gui = MAIN_GUI()
main_gui.show()
main_gui.raise_()
sys.exit(app.exec_())
excel_dummy.py:
import os, pandas as pd
from pandas import ExcelWriter
def excelify():
path = '/tmp/final.xlsx'
with ExcelWriter(path, engine='xlsxwriter') as writer:
workbook = writer.book
worksheet = workbook.add_worksheet()
worksheet.write(2, 2, 'just write something')
writer.save()
print('file size: %s "%s"' % (os.stat(path).st_size, path))
excelify()
MAIN_GUI.py:
from PyQt4 import QtCore,QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.unicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(320,201)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.updateALL_Button = QtGui.QPushButton(self.centralwidget)
self.updateALL_Button.setGeometry(QtCore.QRect(40,110,161,27))
self.updateALL_Button.setFocusPolicy(QtCore.Qt.NoFocus)
self.updateALL_Button.setObjectName(_fromUtf8("Options_updateALL_Button"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 320, 24))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self,MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.updateALL_Button.setText(_translate("MainWindow", "updateALL", None))
Your writer.save() statement is outside the with ExcelWriter(...) as writer: block. Try running it with the statement inside the block.
with ExcelWriter('/home/Desktop/Excelified/final.xlsx', engine='xlsxwriter') as writer:
workbook=writer.book
worksheet=workbook.add_worksheet()
worksheet.write(2,2,'just write something')
writer.save()

pyQt: how to pass information between windows

I have two windows, both containing one button and one lineEdit. I want to create a "ping - pong" communication between both windows. At first, I write something in the lineEdit of the first window, press the button, and a second window appears.
I want the message written in the lineEdit of the first window to appear to the lineEdit of the second window. (and vice versa).
this is the code for the creation of the First window, derived from Qt Designer:
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(331, 249)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.PushButtonFirst = QtGui.QPushButton(self.centralwidget)
self.PushButtonFirst.setGeometry(QtCore.QRect(140, 180, 131, 27))
self.PushButtonFirst.setObjectName(_fromUtf8("PushButtonFirst"))
self.lineEditFirst = QtGui.QLineEdit(self.centralwidget)
self.lineEditFirst.setGeometry(QtCore.QRect(130, 50, 113, 27))
self.lineEditFirst.setObjectName(_fromUtf8("lineEditFirst"))
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.actionNew = QtGui.QAction(MainWindow)
self.actionNew.setObjectName(_fromUtf8("actionNew"))
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
self.actionClose = QtGui.QAction(MainWindow)
self.actionClose.setObjectName(_fromUtf8("actionClose"))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.PushButtonFirst.setText(_translate("MainWindow", "PushButtonFirst", None))
self.actionNew.setText(_translate("MainWindow", "New", None))
self.actionOpen.setText(_translate("MainWindow", "Open", None))
self.actionClose.setText(_translate("MainWindow", "Close", None))
this is the code for the creation of the Second window, derived from Qt Designer:
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(329, 260)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.PushButtonSecond = QtGui.QPushButton(self.centralwidget)
self.PushButtonSecond.setGeometry(QtCore.QRect(130, 190, 121, 27))
self.PushButtonSecond.setObjectName(_fromUtf8("PushButtonSecond"))
self.lineEditSecond = QtGui.QLineEdit(self.centralwidget)
self.lineEditSecond.setGeometry(QtCore.QRect(120, 80, 113, 27))
self.lineEditSecond.setObjectName(_fromUtf8("lineEditSecond"))
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.PushButtonSecond.setText(_translate("MainWindow", "PushButtonSecond", None))
and this is the main code:
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys
import design1, design2
class Second(QtGui.QMainWindow, design2.Ui_MainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.setupUi(self)
class First(QtGui.QMainWindow, design1.Ui_MainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setupUi(self)
self.PushButtonFirst.clicked.connect(self.on_PushButtonFirst_clicked)
self.dialog = Second(self)
def on_PushButtonFirst_clicked(self):
self.my_text_First = self.lineEditFirst.text()
pass_text(self)
self.dialog.show()
def pass_text(obj):
obj.lineEditSecond.setText('OK')
def main():
app = QtGui.QApplication(sys.argv)
main = First()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I receive this message:
'First' object has no attribute 'lineEditSecond'
which is quite logical, since pass_text() is a function of the First class. Anyway, I can't think any workaround.
Any thought would be appreciated.
You pretty much got it working. When I get an attribute error and can't figure it out, I use print type(object) and print dir(object) as a first-line of debugging to double check that the object is what I think it is, and to inspect all of its attributes.
The problem is you were not passing the second dialog whose text you wanted to set. I fixed this, and made a few other minor changes to your First class:
class First(QtGui.QMainWindow, design1.Ui_MainWindow):
def __init__(self, parent=None):
super(First, self).__init__(parent)
self.setupUi(self)
self.PushButtonFirst.clicked.connect(self.on_PushButtonFirst_clicked)
self.partnerDialog = Second(self)
def on_PushButtonFirst_clicked(self):
self.partnerDialog.lineEditSecond.setText(self.lineEditFirst.text())
self.partnerDialog.show()
class Second(QtGui.QMainWindow, design2.Ui_MainWindow):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
self.setupUi(self)
self.PushButtonSecond.clicked.connect(self.on_PushButtonSecond_clicked)
self.partnerDialog = parent #otherwise, recursion
def on_PushButtonSecond_clicked(self):
self.partnerDialog.lineEditFirst.setText(self.lineEditSecond.text())
self.partnerDialog.show()
I have tightened it up to keep things more encapsulated and easier for debugging/thinking/posting here.

Unable to detect undefined names

New to QtDesigner and PyQt and trying to get my first simple application going. (The user enters anywhere from one to three values in LineEdits and the sum is put in a fourth LineEdit). I created the GUI (simpleAdder1.py) with Qt Designer and then wrote the following code (callsimpleAdder1.pyw). Unfortunately it's not running and code analysis suggests a problem at the 'from simpleAdder1 import *' line. The problem is ...."from simpleAdder1 import * ,used, unable to detect undefined names'
I originally thought it was a path problem. But simpleAdder1.py is in the same directory as callsimpleadder1.pyw. I also copied simpleAdder1 into one of the paths that Python checks and that didn't help.
Where am I going wrong ? What names are undefined ? How do I fix this ?
import sys
from simpleAdder1 import *
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui=Ui_Dialog()
self.ui.setupUi(self)
def on_v1Input_textChanged(self):
self.ui.calcResult()
def on_v2Input_textChanged(self):
self.ui.calcResult()
def on_v3Input_textChanged(self):
self.ui.calcResult()
def calcResult(self):
if len(self.ui.v1Input.txt())!=0:
a=float(self.ui.v1Input.txt())
else:
a=0
if len(self.ui.v2Input.txt())!=0:
b=float(self.ui.v2Input.txt())
else:
b=0
if len(self.ui.v3Input.txt())!=0:
c=float(self.ui.v1Input.txt())
else:
c=0
sum=a+b+c
self.ui.calc_result.setText(+str(sum))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp=MyForm()
myapp.show
app.exec_()
The code for the GUI (simpleAdder1) is as follows:
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(673, 565)
self.v1Input = QtGui.QLineEdit(Dialog)
self.v1Input.setGeometry(QtCore.QRect(50, 70, 71, 20))
self.v1Input.setObjectName(_fromUtf8("v1Input"))
self.v2Input = QtGui.QLineEdit(Dialog)
self.v2Input.setGeometry(QtCore.QRect(150, 70, 71, 20))
self.v2Input.setObjectName(_fromUtf8("v2Input"))
self.v3Input = QtGui.QLineEdit(Dialog)
self.v3Input.setGeometry(QtCore.QRect(250, 70, 71, 20))
self.v3Input.setObjectName(_fromUtf8("v3Input"))
self.calc_result = QtGui.QLineEdit(Dialog)
self.calc_result.setGeometry(QtCore.QRect(420, 70, 113, 20))
self.calc_result.setObjectName(_fromUtf8("calc_result"))
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(60, 50, 46, 13))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(160, 50, 46, 13))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(260, 50, 46, 13))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.label_4 = QtGui.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(450, 50, 46, 13))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(200, 230, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.v1Input.clear)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.v2Input.clear)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.v3Input.clear)
QtCore.QMetaObject.connectSlotsByName(Dialog)
#QtCore.QObject.connect(self.v1Input,QtCore.SIGNAL("textChanged"),self.calcResult)
#QtCore.QObject.connect(self.v2Input,QtCore.SIGNAL("textChanged"),self.calcResult)
#QtCore.QObject.connect(self.v3Input,QtCore.SIGNAL("textChanged"),self.calcResult)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label.setText(_translate("Dialog", "Val 1", None))
self.label_2.setText(_translate("Dialog", "Val 2", None))
self.label_3.setText(_translate("Dialog", "Val 3", None))
self.label_4.setText(_translate("Dialog", "Result", None))
self.pushButton.setText(_translate("Dialog", "Clear Inputs", None))
OK, I think I (maybe) understand your problem.
Unfortunately it's not running and code analysis suggests a problem at the 'from simpleAdder1 import *' line. The problem is ...."from simpleAdder1 import * ,used, unable to detect undefined names'
I see your code the problem widget can't show isn't this error I think error this your path file.
But, I use PyDev 2.8.2 on Eclipse Kepler Service Release 1, It have (little) warning unused import like this,
Unused in wild import: QtCore
Found at: simpleAdder1
Then, I suggest to use "used import" only, like this;
from simpleAdder1 import Ui_Dialog, QtGui
And what is going wrong your GUI ? It's because this line in main;
myapp.show
To solve problem, please "Call function" (In old isn't call function anything) like this;
myapp.show()
Regards,

Not show anything from setText() or other showing method in pyqt4 inside of threading class

I write a simple socket app with pyqt4 and threading in python3.3, but i have problem with running Qt classes command like show a message in label or anything, only python code works properly.
Not show anything to S_label in my gui,
I use 2 ways to show any message on S_label but neither of ways not work,
self._ui
self.ui
in code :
self.ui.S_label.setText("test !")
self._ui.S_label.setText("test !")
self.ui.S_label.setText("{0}:{1} is connected.".format(addr, remoport))
for both two ways print works well:
print(self._ui)
print(self.ui)
print output :
-<imigui.Ui_MainWindow object at 0x7fe0746cac10>
-<imigui.Ui_MainWindow object at 0x7fe0746d5d90>
What I'm doing wrong?
my code :
from PyQt4 import QtCore, QtGui
from imigui import Ui_MainWindow
class imiserv(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.Sport_lineEdit.setMaxLength(5)
self.ui.Sconnect_pushButton.clicked.connect(self.serv)
def serv(self):
self.sersock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sersock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host= str(self.ui.Sip_lineEdit.text())
self.port= int(self.ui.Sport_lineEdit.text())
MY_LOCK = threading.Lock()
class CountT(threading.Thread, imiserv):
def __init__(self, ui, ser):
super().__init__()
imiserv.__init__(self)
self._sersock= ser
self._ui= ui
print(self._ui)
print(self.ui)
self.ui.S_label.setText("test !")
self._ui.S_label.setText("test !")
def run(self):
MY_LOCK.acquire()
while True:
cliconn, (addr, remoport)= self._sersock.accept()
self.cstr= cliconn.recv(1024)
self.ui.S_label.setText("{0}:{1} is connected.".format(addr, remoport))
cliconn.close()
print(self.cstr)
MY_LOCK.release()
try :
self.sersock.bind((self.host, self.port))
self.sersock.listen(5)
a= CountT(self.ui, self.sersock)
a.daemon= True # for exit from thread when close gui
a.start()
except socket.error as err:
self.ui.S_label.setText(err)
Edit(new problem) :
I have a new problem with your way:i added a qtextedit to my gui and when i want to settext to it in my code Segmentation fault happened and app crashed ,
error :
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x15c4460), parent's thread is QThread(0xfeb570), current thread is QThread(0x15d3900)
Segmentation fault
My Code:
from PyQt4 import QtCore, QtGui
from imigui import Ui_MainWindow
class imiserv(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.Sport_lineEdit.setMaxLength(5)
self.ui.Sconnect_pushButton.clicked.connect(self.serv)
def serv(self):
self.sersock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sersock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host= str(self.ui.Sip_lineEdit.text())
self.port= int(self.ui.Sport_lineEdit.text())
MY_LOCK = threading.Lock()
class CountT(threading.Thread):
def __init__(self, label, ser, qtext):
super().__init__()
self._sersock= ser
self._uilabel= label
self._uiClog= qtext
def run(self):
MY_LOCK.acquire()
while True:
cliconn, (addr, remoport)= self._sersock.accept()
self.cstr= cliconn.recv(1024)
self._uilabel.setText("{0}:{1} is connected.".format(addr, remoport))
cliconn.close()
print(self.cstr)
self._uilabel.setText(self.cstr) # it's ok!
self._uiClog.setText(msg) # Segmentation fault
MY_LOCK.release()
try :
self.sersock.bind((self.host, self.port))
self.sersock.listen(5)
a= CountT(label= self.ui.S_label, ser= self.sersock, qtext= self.ui.Clog_textEdit)
a.daemon= True # for exit from thread when close gui
a.start()
self.ui.S_label.setText("Connected !")
except socket.error as err:
self.ui.S_label.setText(err) # it's ok !
self.ui.self.ui.Clog_textEdit.setText(err) # it's ok !
Why ?
Edit(new problem2) :
this is my code :
from PyQt4 import QtCore, QtGui
from imigui import Ui_MainWindow
class imiserv(QtGui.QMainWindow):
send_msg = pyqtSignal('QString', 'QString')
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.Sport_lineEdit.setMaxLength(5)
self.ui.Sconnect_pushButton.clicked.connect(self.serv)
self.send_msg.connect(self.write_msg)
def write_msg(self, lbl_msg= None, txt_msg= None):
if lbl_msg:
self.ui.C_label.setText(lbl_msg)
if txt_msg:
self.ui.Clog_textEdit.setText(txt_msg)
def serv(self):
MY_LOCK = threading.Lock()
class CountT(threading.Thread):
def __init__(self, parent):
threading.Thread.__init__(self)
self._parent= parent
def run(self):
MY_LOCK.acquire()
self._parent.send_msg.emit("Waiting connections","")
while True:
cliconn, (addr, remoport)= self._parent.clis.accept()
clirecmsg= str(cliconn.recv(1024)
self._parent.send_msg.emit("{0}:{1} is connected.".format(addr, remoport), "{0}:{1}".format(addr, remoport)
cliconn.close()
MY_LOCK.release()
try :
self.clis= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.clis.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
clierhost= str(self.ui.Sip_lineEdit.text())
clierport= int(self.ui.Sport_lineEdit.text())
self.clis.bind((clierhost, clierport))
self.clis.listen(5)
a= CountT(self)
a.daemon= True
a.start()
except socket.error as err:
err= str(err)
print(err)
and this is error that happened decussate, i should press button twice for get event for first time error showed in linux and nothing in windows and for second press event is happened,(this error show only in linux os.)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.3/threading.py", line 637, in _bootstrap_inner
self.run()
File "imiclilap.py", line 34, in run
cliconn, (addr, remoport)= self._parent.clis.accept()
File "/usr/lib/python3.3/socket.py", line 135, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.3/threading.py", line 637, in _bootstrap_inner
self.run()
File "imiclilap.py", line 34, in run
cliconn, (addr, remoport)= self._parent.clis.accept()
File "/usr/lib/python3.3/socket.py", line 135, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
The following code works for me (Python 2.6 here). I removed the inheritance of CountT with imiserv and replaced the ui object by the QLabel S_label the imiserv instance instead. A pyqtsignal allows the thread CounT to write text to the QLabel and the QTextEdit:
import socket
import threading
from PyQt4 import QtCore, QtGui
from imigui import Ui_MainWindow
class imiserv(QtGui.QMainWindow):
send_msg = pyqtSignal('QString', 'QString')
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.Sport_lineEdit.setMaxLength(5)
self.ui.Sconnect_pushButton.clicked.connect(self.serv)
self.send_msg.connect(self.my_slot)
def write_msg(self, lbl_msg, txt_msg):
self.ui.S_label.setText(lbl_msg)
self.ui.Clog_textEdit.setText(txt_msg)
def serv(self):
self.sersock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sersock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.host= str(self.ui.Sip_lineEdit.text())
self.port= int(self.ui.Sport_lineEdit.text())
MY_LOCK = threading.Lock()
class CountT(threading.Thread):
def __init__(self, parent):
threading.Thread.__init__(self)
self._parent= parent
def run(self):
MY_LOCK.acquire()
self._parent.send_msg.emit("Waiting connections","")
while True:
cliconn, (addr, remoport)= self.__parent.sersock.accept()
self.cstr= cliconn.recv(1024)
self._parent.send_msg.emit("{0}:{1} is connected.".format(addr, remoport), self.cstr)
cliconn.close()
MY_LOCK.release()
try :
self.sersock.bind((self.host, self.port))
self.sersock.listen(5)
a= CountT(self)
a.daemon= True # for exit from thread when close gui
a.start()
except socket.error as err:
self.ui.S_label.setText(err.strerror.decode("utf-8"))
self.ui.Clog_textEdit.setText(err.strerror.decode("utf-8"))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
s = imiserv()
s.show()
sys.exit(app.exec_())

Resources