program close when open csv file in qtable - python

when I added function for a button to show data in CSV file when I click the program, it closes itself. I altered my code, however, the same problem persists.
Debug does not show any error messages. I'm a beginner in qt and if there alternatives to qtablewidget or better ways to tackle this, please let me know.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'officer.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
import sys
import csv
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(QtWidgets.QWidget):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(930, 650)
self.fname = "data.csv"
self.combo_data2 = {0: ['إيهاب السيد محمود السيد'],
1: ['محمد مدحت محمد', 'محمد عبدالرؤوف متولي', 'وليد عزت عبدالمؤمن', 'هاني حسنين أحمد حسنين',
'محمود السيد سليمان'], 2: ['حازم فتحي مختار', 'أمير محمود سيد', 'أحمد عبدالجليل'],
3: ['ابراهيم مختار عبدالقوي', "أحمد عفيفي محمود عفيفي", 'محمود عبدالعزيز عبدالحميد',
'حسام جابر عبدالعزيز', 'إسلام مصطفى محمد', 'محمد عطيوة عبدالرازق'],
4: ["إسلام عبدالرحمن حسن", "محمد عبدالمنعم محمد يونس", 'محمد فتحي عبدالوهاب',
'محمود عبدالسلام', 'عاصم عادل عبدالعزيز'],
5: ["أحمد محمد عزت", "محمد رضا عبدالعظيم", "أحمد رمضان موسى", "عمر عناني عناني",
"حازم سامي ابراهيم", 'عبدالرحمن سمير ', 'أحمد محمد ابراهيم', 'محمد أحمد عايش',
'سعيد مدحت رأفت', 'أحمد محمد محمود البقري', 'وليد ابراهيم عبدالمجيد',
'محمد عبدالحميد سالم', 'حاتم محمد نجيب'], 6: ["محمود سامي عبدالغفار شعير"]}
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(190, 60, 75, 22))
self.pushButton.setObjectName("pushButton")
self.pushButton1 = QtWidgets.QPushButton(Form)
self.pushButton1.setGeometry(QtCore.QRect(50, 110, 85, 22))
self.pushButton1.setObjectName("pushButton1")
self.pushButton2 = QtWidgets.QPushButton(Form)
self.pushButton2.setGeometry(QtCore.QRect(150, 110, 85, 22))
self.pushButton2.setObjectName("pushButton2")
self.tableWidget = QtWidgets.QTableWidget(Form)
self.tableWidget.setEnabled(True)
self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers) # Make table not editable
self.tableWidget.setGeometry(QtCore.QRect(25, 151, 881, 471))
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(4)
self.tableWidget.setRowCount(38)
self.col_headers = ['الرتبة', 'الإسم', 'رصيد سنوية', 'رصيد عارضة']
self.tableWidget.setHorizontalHeaderLabels(self.col_headers)
self.tableWidget.setLayoutDirection(QtCore.Qt.RightToLeft)
header = self.tableWidget.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
self.comboBox = QtWidgets.QComboBox(Form)
self.comboBox.setGeometry(QtCore.QRect(728, 60, 121, 22))
self.comboBox.setEditable(False)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox_2 = QtWidgets.QComboBox(Form)
self.comboBox.setLayoutDirection(QtCore.Qt.RightToLeft)
self.comboBox_2.setLayoutDirection(QtCore.Qt.RightToLeft)
self.comboBox_2.setGeometry(QtCore.QRect( 348, 60, 311, 22))
self.comboBox_2.setEditable(False)
self.comboBox_2.setCurrentText("")
self.comboBox_2.setObjectName("comboBox_2")
self.tableWidget.raise_()
self.pushButton.raise_()
self.comboBox.raise_()
self.comboBox_2.raise_()
self.set_combo()
self.comboBox.currentIndexChanged.connect(self.set_combo)
self.pushButton.clicked.connect(self.open_csv)
self.retranslateUi(Form)
self.comboBox.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(Form)
def open_csv(self):
with open(self.fname , 'r') as record :
for row_data in csv.reader(record):
row = self.tableWidget.rowCount()
self.tableWidget.insertRow(row)
for col , data in enumerate(row_data):
item = QtGui.QTextTableCellFormat(data)
self.tableWidget.setItem( row , col, item)
def search(self):
print 'search'
def set_combo(self):
self.comboBox_2.clear()
x = self.comboBox.currentIndex()
self.comboBox_2.addItems(self.combo_data2[x])
print x
print type(x)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "بيانات الضباط"))
self.pushButton.setText(_translate("Form", "بحث"))
self.pushButton1.setText(_translate("Form", "خصم عارضة"))
self.pushButton2.setText(_translate("Form", "خصم سنوية"))
self.comboBox.setToolTip(_translate("Form", "<html><head/><body><p>الرتبة</p></body></html>"))
self.comboBox.setCurrentText(_translate("Form", "الرتبة"))
self.comboBox_2.setCurrentText(_translate("Form", "الإسم"))
self.comboBox.setItemText(0, _translate("Form", "عميد"))
self.comboBox.setItemText(1, _translate("Form", "عقيد"))
self.comboBox.setItemText(2, _translate("Form", "مقدم"))
self.comboBox.setItemText(3, _translate("Form", "رائد"))
self.comboBox.setItemText(4, _translate("Form", "نقيب"))
self.comboBox.setItemText(5, _translate("Form", "ملازم أول"))
self.comboBox.setItemText(6, _translate("Form", "ملازم"))
self.comboBox_2.setToolTip(_translate("Form", "<html><head/><body><p>الإسم</p></body></html>"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())

I do not understand why you use QTextTableCellFormat, QTableWidget expects a QTableWidgetItem:
def open_csv(self):
self.tableWidget.setRowCount(0)
with open(self.fname , 'r') as record :
for row_data in csv.reader(record):
row = self.tableWidget.rowCount()
self.tableWidget.insertRow(row)
for col , data in enumerate(row_data):
item = QtWidgets.QTableWidgetItem(data)
self.tableWidget.setItem( row , col, item)

Related

GUI freezes on sleep from a worker [duplicate]

This question already has answers here:
time.sleep() and BackGround Windows PyQt5
(1 answer)
Equivalent to time.sleep for a PyQt application
(5 answers)
Closed 2 years ago.
I have created a big project involving communication with a controller via serial port.
My project is divided to 3 files:
File A - a pyqt5 designer file - including all my buttons, line edits, etc.
File B - a serial communication file - basically ask questions and receive answers from the controller.
File C - the main file; in this file I am importing file A and file B and using them.
In file C, I have created a worker, so all the communications with the controller are being made by this thread. (using the class and functions of file B..)
Now, I am trying to make a create a new function within the worker. The functions is using time.sleep every x seconds for y times. From what I understand, because I am using a thread, the GUI should not get stuck, but for some reason, it does.
Since the code is very long, I have only attaching what I think is relevant to the question.
I tried to copy as little of the code, yet still keep it understandable, I hope it's ok.
File A - pyqt5 designer code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
################creating general veriables#####################
MainWindow.setObjectName("MainWindow")
MainWindow.setFixedSize(780, 585)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
MainWindow.setFont(font)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame_Holder = QtWidgets.QFrame(self.centralwidget)
self.frame_Holder.setGeometry(QtCore.QRect(0, 85, 780, 500))
self.frame_Holder.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_Holder.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_Holder.setObjectName("frame_Holder")
#########################################################################
################creating veriables for the Top Frame#####################
self.frame_Top = QtWidgets.QFrame(self.centralwidget)
self.frame_Top.setEnabled(True)
self.frame_Top.setGeometry(QtCore.QRect(10, 5, 760, 80))
font = QtGui.QFont()
font.setStrikeOut(False)
self.frame_Top.setFont(font)
self.frame_Top.setFrameShape(QtWidgets.QFrame.WinPanel)
self.frame_Top.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_Top.setLineWidth(1)
self.frame_Top.setObjectName("frame_Top")
################creating Buttons#####################
self.btn_Connect = QtWidgets.QPushButton(self.frame_Top)
self.btn_Connect.setGeometry(QtCore.QRect(85, 50, 75, 23))
self.btn_Connect.setObjectName("btn_Connect")
self.btn_Connect.setEnabled(False)
self.btn_PortList = QtWidgets.QPushButton(self.frame_Top)
self.btn_PortList.setGeometry(QtCore.QRect(10, 50, 65, 23))
self.btn_PortList.setObjectName("btn_PortList")
self.productMenu=QtWidgets.QMenu(self.frame_Top)
self.btn_PortList.setMenu(self.productMenu)
self.btn_Init = QtWidgets.QPushButton(self.frame_Top)
self.btn_Init.setEnabled(False)
self.btn_Init.setGeometry(QtCore.QRect(300, 50, 75, 23))
self.btn_Init.setObjectName("btn_Init")
################creating text edits#####################
self.edit_version = QtWidgets.QLineEdit(self.frame_Top)
self.edit_version.setGeometry(QtCore.QRect(170, 50, 120, 23))
self.edit_version.setObjectName("edit_version")
self.edit_version.setEnabled(False)
################creating labels#####################
self.lbl_Version = QtWidgets.QLabel(self.frame_Top)
self.lbl_Version.setGeometry(QtCore.QRect(170, 30, 71, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.lbl_Version.setFont(font)
self.lbl_Version.setObjectName("lbl_Version")
self.lbl_FrameTop = QtWidgets.QLabel(self.frame_Top)
self.lbl_FrameTop.setEnabled(True)
self.lbl_FrameTop.setGeometry(QtCore.QRect(5, 5, 90, 25))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
font.setStrikeOut(False)
font.setKerning(True)
self.lbl_FrameTop.setFont(font)
self.lbl_FrameTop.setObjectName("lbl_FrameTop")
self.lbl_On = QtWidgets.QLabel(self.frame_Top)
self.lbl_On.setGeometry(QtCore.QRect(528, 30, 41, 16))
self.lbl_On.setObjectName("lbl_On")
self.lbl_Enable = QtWidgets.QLabel(self.frame_Top)
self.lbl_Enable.setGeometry(QtCore.QRect(560, 30, 41, 16))
self.lbl_Enable.setObjectName("lbl_Enable")
self.lbl_Rls = QtWidgets.QLabel(self.frame_Top)
self.lbl_Rls.setGeometry(QtCore.QRect(608, 30, 41, 16))
self.lbl_Rls.setObjectName("lbl_Rls")
self.lbl_Chk = QtWidgets.QLabel(self.frame_Top)
self.lbl_Chk.setGeometry(QtCore.QRect(645, 30, 41, 16))
self.lbl_Chk.setObjectName("lbl_Chk")
self.lbl_Wafer = QtWidgets.QLabel(self.frame_Top)
self.lbl_Wafer.setGeometry(QtCore.QRect(683, 30, 41, 16))
self.lbl_Wafer.setObjectName("lbl_Wafer")
self.lbl_Err = QtWidgets.QLabel(self.frame_Top)
self.lbl_Err.setGeometry(QtCore.QRect(725, 30, 20, 16))
self.lbl_Err.setObjectName("lbl_Err")
self.lbl_Port = QtWidgets.QLabel(self.frame_Top)
self.lbl_Port.setGeometry(QtCore.QRect(10, 30, 51, 21))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
self.lbl_Port.setFont(font)
self.lbl_Port.setObjectName("lbl_Port")
#########################################################################
self.frame_AutoRun = QtWidgets.QFrame(self.frame_Holder)
self.frame_AutoRun.setEnabled(False)
self.frame_AutoRun.setGeometry(QtCore.QRect(10, 90, 760, 320))
font = QtGui.QFont()
self.frame_AutoRun.setFont(font)
self.frame_AutoRun.setFrameShape(QtWidgets.QFrame.WinPanel)
self.frame_AutoRun.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_AutoRun.setLineWidth(1)
self.frame_AutoRun.setObjectName("frame_AutoRun")
self.lbl_AutoRun = QtWidgets.QLabel(self.frame_AutoRun)
self.lbl_AutoRun.setGeometry(QtCore.QRect(5, 5, 110, 25))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
font.setStrikeOut(False)
font.setKerning(True)
self.lbl_AutoRun.setFont(font)
self.lbl_AutoRun.setObjectName("lbl_AutoRun")
self.btn_RunStop = QtWidgets.QPushButton(self.frame_AutoRun)
self.btn_RunStop.setGeometry(QtCore.QRect(500, 40, 60, 23))
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(False)
font.setWeight(50)
font.setKerning(True)
self.btn_RunStop.setFont(font)
self.btn_RunStop.setObjectName("btn_RunStop")
########################4##########################
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "ECC GUI"))
self.btn_Connect.setText(_translate("MainWindow", "Connect"))
self.btn_PortList.setText(_translate("MainWindow", "Ports"))
self.lbl_Version.setText(_translate("MainWindow", "Version"))
self.btn_Init.setText(_translate("MainWindow", "Initiate"))
self.lbl_FrameTop.setText(_translate("MainWindow", "Connect"))##########
self.lbl_Port.setText(_translate("MainWindow", "Ports"))
self.lbl_On.setText(_translate("MainWindow", "ON"))
self.lbl_Enable.setText(_translate("MainWindow", "Enable"))
self.lbl_Rls.setText(_translate("MainWindow", "RLS"))
self.lbl_Chk.setText(_translate("MainWindow", "CHK"))
self.lbl_Wafer.setText(_translate("MainWindow", "Wafer"))
self.lbl_Err.setText(_translate("MainWindow", "ERR"))
self.lbl_AutoRun.setText(_translate("MainWindow", "Auto Run"))
self.btn_RunStop.setText(_translate("MainWindow", "Run"))
File B - the serial communication file
import serial
from string import hexdigits
from re import search
class ECC():
def __init__(self,Port ):
self.ser = serial.Serial(port ='COM'+str(Port), baudrate= 38400,timeout=1)
def cmd(self,command):
return ('00'+command+chr(13)).encode('utf-8')
def disconnect(self):
self.ser.close()
def init(self):
self.ser.write(self.cmd('INI'))
return(self.ser.readline().decode('utf-8')[:3])
def spr(self,address,value):
self.ser.write(self.cmd('SPR'+str(address)+str(value)))
return (self.ser.readline().decode('utf-8')[:3])
def rpr(self,address):
self.ser.write(self.cmd('RPR'+str(address)))
return(self.ser.readline().decode('utf-8')[3:7])
def chuck(self):
self.ser.write(self.cmd('CHK'))
return(self.ser.readline().decode('utf-8')[:3])
def rls(self):
self.ser.write(self.cmd('RLS'))
return(self.ser.readline().decode('utf-8')[:3])
def cap(self):
self.ser.write(self.cmd('cap'))
cap=self.ser.readline()[3:].decode('utf-8')
cap=cap.rstrip()
if (all(c in hexdigits for c in cap) and cap!=""):
return int(cap,16)
else:
return("Busy...")
def version(self):
self.ser.write(self.cmd('VER'))
return(self.ser.readline().decode('utf-8')[:9])
def gst(self):
self.ser.flushInput()
self.ser.flushOutput()
self.ser.write(self.cmd('GST'))
gst=self.ser.readline()
gst=gst.decode('utf-8')
is_STV=search('^STV',str(gst))
if (is_STV):
stat_hex=gst[3:]
stat_bin=(bin(int(stat_hex,16))[2:].zfill(16))
stat_bool=[bool(int(bit)) for bit in stat_bin]
else:
stat_hex="ERR"
stat_bool="ERR"
return stat_hex, stat_bool
def statLights(self):
[stat_hex, stat_bool]=self.gst()
if(not stat_hex=="ERR"):
lights=[not(stat_bool[3]),not(stat_bool[5]),not(stat_bool[10]),stat_bool[10],stat_bool[11],stat_bool[0]]
else:
lights="ERR"
return lights
def msrphys(self):
self.ser.flushInput()
self.ser.flushOutput()
self.ser.write(self.cmd('msr'))
A=list()
A.append(self.ser.readline())
A[0]=A[0][3:7]
exists=search('[0-9A-Fa-f]{4}',str(A[0]))
if(exists):
A[0]=int(A[0],16)*-0.08398628+2500
for ind in range(1,32):
A.append(self.ser.readline())
exists=search('[0-9A-Fa-f]{4}',str(A[ind]))
if (exists):
A[ind]=int(A[ind].decode('utf-8'),16)*-0.08398628+2500
else:
A[0]="ERR"
break
self.ser.readline()
A[12]=A[12]*5.75
A[13]=A[13]*5.75
A[14]=A[14]*0.1
else:
A[0]="ERR"
return A
File C - the operative file
from test_des import Ui_MainWindow
from PyQt5 import QtWidgets, QtCore, QtGui
from test_serialCom import ECC
import serial.tools.list_ports
import sys
from re import findall
import time
from functools import partial
try:
import queue
except ImportError:
import Queue as queue
class eccWorker(QtCore.QRunnable):
def __init__(self,port,q):
super(eccWorker, self).__init__()
self.finished = QtCore.pyqtSignal()
self.port=port
self.Q=q
self.threadactive=True
def run(self):
if(self.threadactive==True):
try:
self.ecc=ECC(self.port)
except:
self.threadactive=False
self.Q.put("ERROR-Not connected")
self.Q.put("ERROR-Not connected")
else:
self.Q.put(self.ecc.version())
self.Q.put(self.ecc.rpr('04'))
def init(self):
if(self.threadactive):
self.ecc.init()
def disconnect(self):
self.ecc.disconnect()
self.threadactive=False
def readCap(self):
if(self.threadactive==True):
self.Q.put(self.ecc.cap())
def chk(self):
if(self.threadactive==True):
self.ecc.chuck()
def rls(self):
if(self.threadactive==True):
self.ecc.rls()
def rprWorker(self,par):
if(self.threadactive==True):
self.Q.put(self.ecc.rpr(par))
def sprWorker(self,par,val):
if(self.threadactive==True):
# par=par.zfill(2)
isOk=self.ecc.spr(par,val)
if (isOk!="NAK"):
self.Q.put(self.ecc.rpr(par))
def getStat(self):
if(self.threadactive==True):
statLight=self.ecc.statLights()
if(statLight=="ERR"):
self.Q.put("ERR")
else:
for i in statLight:
self.Q.put(i)
def sprWorkerNoRpr(self,par,val):
if(self.threadactive==True):
isOk=self.ecc.spr(par,val)
if (isOk!="NAK"):
return True
def test1(self,Vchk,N,dt,Dt,threshold):
Vchk=str(Vchk).zfill(4)
if(self.sprWorkerNoRpr('04',Vchk)):
cap1=list()
cap2=list()
for i in range(N):
self.rls()
time.sleep(dt)
self.readCap()
res=self.Q.get()
if (res!="Busy..."):
cap1.append(int(str(res)))
time.sleep(Dt)
self.chk()
time.sleep(dt)
self.readCap()
res2=self.Q.get()
if (res2!="Busy..."):
cap2.append(int(str(res2)))
time.sleep(Dt)
self.rls()
cap_Rls=sum(cap1)/len(cap1)
cap_Chk=sum(cap2)/len(cap2)
if((max(cap2)-min(cap1))>threshold):
isPass=True
else:
isPass=False
self.Q.put(cap_Rls)
self.Q.put(cap_Chk)
self.Q.put(isPass)
print("Done!")
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super(ApplicationWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.threadpool=QtCore.QThreadPool()
self.Q=queue.Queue()
self.ui.productMenu.aboutToShow.connect(self.findPort)
self.ui.btn_Connect.clicked.connect(self.connectClicked)
self.ui.btn_RunStop.clicked.connect(self.run)
self.ui.btn_Init.clicked.connect(self.initClicked)
self.redOff=QtGui.QColor(120,0,0)
self.redOn=QtGui.QColor(255,0,0)
self.grnOff=QtGui.QColor(7,100,0)
self.grnOn=QtGui.QColor(16,243,0)
self.yelOff=QtGui.QColor(155,80,0)
self.yelOn=QtGui.QColor(255,127,0)
self.onPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.enablePen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.rlsPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.chkPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.waferPen=QtGui.QPen(self.yelOff, 8, QtCore.Qt.SolidLine)
self.errPen=QtGui.QPen(self.redOff, 8, QtCore.Qt.SolidLine)
def paintEvent(self, e):
onLedPainter = QtGui.QPainter(self)
onLedPainter.setPen(self.onPen)
onLedPainter.setBrush(self.grnOff)
onLedPainter.drawEllipse(540,55,10,10)
enabledLedPainter = QtGui.QPainter(self)
enabledLedPainter.setPen(self.enablePen)
enabledLedPainter.setBrush(self.grnOff)
enabledLedPainter.drawEllipse(580,55,10,10)
rlsLedPainter = QtGui.QPainter(self)
rlsLedPainter.setPen(self.rlsPen)
rlsLedPainter.setBrush(self.grnOff)
rlsLedPainter.drawEllipse(620,55,10,10)
chkLedPainter = QtGui.QPainter(self)
chkLedPainter.setPen(self.chkPen)
chkLedPainter.setBrush(self.grnOff)
chkLedPainter.drawEllipse(660,55,10,10)
waferLedPainter = QtGui.QPainter(self)
waferLedPainter.setPen(self.waferPen)
waferLedPainter.setBrush(self.yelOff)
waferLedPainter.drawEllipse(700,55,10,10)
errLedPainter = QtGui.QPainter(self)
errLedPainter.setPen(self.errPen)
errLedPainter.setBrush(self.redOff)
errLedPainter.drawEllipse(740,55,10,10)
def updateStat(self):
#####updating LEDs####
self.worker.getStat()
self.ledStat=list()
self.ledStat.append(self.worker.Q.get())
if(not self.ledStat[0]=="ERR"):
for i in range(5):
self.ledStat.append(self.worker.Q.get())
if(self.ledStat[0]):
self.onPen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
else:
self.onPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[1]):
self.enablePen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
else:
self.enablePen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[2]):
self.rlsPen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
self.chkPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
else:
self.chkPen=QtGui.QPen(self.grnOn, 8, QtCore.Qt.SolidLine)
self.rlsPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[4]):
self.waferPen=QtGui.QPen(self.yelOn, 8, QtCore.Qt.SolidLine)
else:
self.waferPen=QtGui.QPen(self.yelOff, 8, QtCore.Qt.SolidLine)
if(self.ledStat[5]):
self.errPen=QtGui.QPen(self.redOn, 8, QtCore.Qt.SolidLine)
else:
self.errPen=QtGui.QPen(self.redOff, 8, QtCore.Qt.SolidLine)
self.update()
else:
self.connectClicked()
self.ui.edit_version.setText("GST Disconnected!")
def findPort(self):
self.ui.productMenu.clear()
comPorts = list(serial.tools.list_ports.comports()) # get a list of all devices connected through serial port
comPorts=sorted(comPorts)
for port in comPorts:
self.ui.productMenu.addAction(str(port),self.selectedPort)
def selectedPort(self):
self.portNum=self.sender()
self.portNum=self.portNum.text()
self.portNum=findall("COM\d+",self.portNum)
self.ui.btn_PortList.setText(str(self.portNum[0]))
self.portNum=self.portNum[0][3:]
self.ui.btn_Connect.setEnabled(True)
def connectClicked(self):
if (self.ui.btn_Connect.text()=="Connect"):
self.worker=eccWorker(self.portNum,self.Q)
self.threadpool.start(self.worker)
ver=self.worker.Q.get()
volHex=self.worker.Q.get()
if(ver[:3]=="VER"):
self.ui.btn_Connect.setText("Disconnect")
self.ui.btn_PortList.setEnabled(False)
self.ui.edit_version.setText(ver)
self.ui.btn_Init.setEnabled(True)
self.ui.frame_AutoRun.setEnabled(True)
self.timer_updateStat = QtCore.QTimer()
self.timer_updateStat.setInterval(500)
self.timer_updateStat.timeout.connect(self.updateStat)
self.timer_updateStat.start()
else:
self.ui.edit_version.setText("Error!")
else:
self.timer_updateStat.stop()
self.worker.disconnect()
self.ui.btn_Connect.setText("Connect")
self.ui.btn_Connect.setEnabled(False)
self.ui.btn_Init.setEnabled(False)
self.ui.frame_AutoRun.setEnabled(False)
self.ui.btn_PortList.setEnabled(True)
self.ui.edit_version.clear()
self.setFixedSize(780,585)
self.ui.btn_PortList.setText("Ports")
self.onPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.enablePen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.chkPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.rlsPen=QtGui.QPen(self.grnOff, 8, QtCore.Qt.SolidLine)
self.waferPen=QtGui.QPen(self.yelOff, 8, QtCore.Qt.SolidLine)
self.errPen=QtGui.QPen(self.redOff, 8, QtCore.Qt.SolidLine)
self.update()
def initClicked(self):
self.worker.init()
def run(self):
self.worker.test1(200,5,0.2,0.3,100)
cap_Rls=self.Q.get()
cap_Chk=self.Q.get()
ispass=self.Q.get()
print("cap_Rls:\n")
print(cap_Rls)
print("cap_Chk:\n")
print(cap_Chk)
print(ispass)
def closeEvent(self,event):
try:
self.worker.disconnect()
finally:
sys.exit()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
application = ApplicationWindow()
application.show()
sys.exit(app.exec_())
So what does the GUI gets stuck for the time of the function even though I am using a thread? What can I do to fix this?
Also, ideally, I would want to have another file, file D, that contains a main class called TESTS,and it has like 5 functions within it, each one represents a test.
The problem I faced doing the above, is failing to calling/getting information from the thread active in file C, so if you have an idea of how to make this one as well, it would be much appreciated. (if not creating another file, so store all the tests in a different class. Here, as well, I faced some issues and could not make it work).
After many many hours of searching online, I found that using QtTest.QTest.qWait(msecs)
instead of sleep is giving me the wanted result - it holds the commands but does not make the GUI freeze.
In order to use it I had to use from PyQt5 import QtTest.
If anyone has yet a better suggestions (to any of the questions above) I would love to see them.

Issue with Timer scope in PyQt5

I am creating an oven monitoring program, that reaches out to some PID controllers over Modbus TCP. I am trying to implement an email alerting part that will monitor the temperature and if it's within tolerance. If it goes out of tolerance it is to send an email and then send another every 10 mins after that it stays out of tolerance. I am sure that I have something screwed up in my scope, but for the life of me I cannot figure out what. When the oven goes out of tolerance my 'inTolerance' function goes to work. It sends 1 email and should start the timer, but my 'is_alive' call does not return true. So when 'inTolerance' calls again it send another email and then bombs out as I believe it attempts to start another 't' timer.
Any help and a sanity check would be extremely helpful and appreciated.
from PyQt5 import QtCore, QtGui, QtWidgets
from modbusTest import Oven
from emailModule import emailer
import time
from threading import Timer
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(170, 260)
self.spinBox = QtWidgets.QSpinBox(Form)
self.spinBox.setGeometry(QtCore.QRect(10, 90, 61, 20))
self.spinBox.setObjectName("setpoint")
self.lcdNumber = QtWidgets.QLCDNumber(Form)
self.lcdNumber.setGeometry(QtCore.QRect(10, 10, 150, 60))
self.lcdNumber.setObjectName("lcdNumber")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(120, 89, 41, 22))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(10, 130, 105, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.spinBox_2 = QtWidgets.QSpinBox(Form)
self.spinBox_2.setGeometry(QtCore.QRect(77, 90, 35, 20))
self.spinBox_2.setObjectName("tolerance")
self.spinBox_2.setValue(5)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(20, 70, 41, 15))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(10, 112, 71, 16))
self.label_2.setObjectName("label_2")
self.listWidget = QtWidgets.QListWidget(Form)
self.listWidget.setGeometry(QtCore.QRect(10, 160, 150, 91))
self.listWidget.setObjectName("listWidget")
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(70, 70, 51, 16))
self.label_3.setObjectName("label_3")
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(120, 129, 40, 22))
self.pushButton_2.setObjectName("pushButton_2")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.p1 = Oven('IP')
self.p1.connect()
self.lcdNumber.display(self.p1.readTemp())
#print(self.t.is_alive())
#self.t.start()
#print(self.t.is_alive())
#TODO set spinbox values to database table values
########################################################################################################
self.tolerance = float(self.spinBox_2.value())
self.spinBox.setValue(self.p1.readSP())
self.setPoint = float(self.spinBox.value())
########################################################################################################
self.pushButton.clicked.connect(self.setter)
QtCore.QTimer.singleShot(1000, self.displayer)
self.pushButton_2.clicked.connect(self.emailerList)
self.emailList = []
self.t = Timer(10.0, None)
def emailerList(self):
if len(self.lineEdit.text()) == 0:
None
else:
self.emailList.append(self.lineEdit.text())
self.listWidget.addItem(self.lineEdit.text())
self.lineEdit.clear()
def displayer(self):
temp = self.p1.readTemp()
self.lcdNumber.display(temp)
self.inTolerance(self.tolerance, temp, self.setPoint)
QtCore.QTimer.singleShot(1000, self.displayer)
def setter(self):
self.setPoint = float(self.spinBox.value())
self.p1.writeSP(self.setPoint)
self.tolerance = float(self.spinBox_2.value())
def inTolerance(self, tolerance, temp, setPoint):
if temp > (setPoint + tolerance) or temp < (setPoint - tolerance):
self.lcdNumber.setStyleSheet("background-color: rgb(255, 0, 0);")
print(self.t.is_alive())
if not self.t.is_alive():
emailer(self.emailList, 'Test Oven', temp, setPoint)
print('Email Sent')
self.t.start()
time.sleep(1)
print(self.t.is_alive())
else:
self.t.cancel()
self.lcdNumber.setStyleSheet("background-color: rgb(255, 255, 255);")
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "Set"))
self.label.setText(_translate("Form", "Setpoint"))
self.label_2.setText(_translate("Form", "Alarm Emails:"))
self.label_3.setText(_translate("Form", "Tolerance"))
self.pushButton_2.setText(_translate("Form", "Add"))
if __name__ == "__main__":
import sys
sys_argv = sys.argv
sys_argv += ['--style', 'Fusion']
app = QtWidgets.QApplication(sys_argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
The main reason of your issue is that you're calling cancel(), which causes the timer to invalidate itself even if it has not been started yet, and the result is that after this the timer will be never actually started.
After that there is another problem: Thread objects can only be started once, and you would need to create a new Timer object whenever you want to start it again.
That said, you should not mix timer objects, and when dealing with threads it's usually better to use what Qt provides.
In your case, the solution is to use a QElapsedTimer, which is an object that can return the elapsed time since it was (re)started.
Note that I'm using a QWidget class (and simplified the ui just for this example), more about that after the code.
class Window(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.resize(170, 260)
layout = QtWidgets.QGridLayout(self)
self.lcdNumber = QtWidgets.QLCDNumber(self)
layout.addWidget(self.lcdNumber, 0, 0, 1, 2)
self.spinBox = QtWidgets.QSpinBox(self)
layout.addWidget(self.spinBox, 1, 0)
self.spinBox_2 = QtWidgets.QSpinBox(self)
layout.addWidget(self.spinBox_2, 1, 1)
self.spinBox_2.setValue(5)
self.p1 = Oven('P1')
self.p1.connect()
self.lcdNumber.display(self.p1.readTemp())
self.tolerance = float(self.spinBox_2.value())
self.setPoint = float(self.spinBox.value())
self.emailList = []
# create a timer that will call displayer each second; having a reference
# to the timer allows to stop it if required
self.displayerTimer = QtCore.QTimer(interval=1000, timeout=self.displayer)
self.displayerTimer.start()
self.elapsedTimer = QtCore.QElapsedTimer()
def displayer(self):
temp = self.p1.readTemp()
self.lcdNumber.display(temp)
self.inTolerance(self.tolerance, temp, self.setPoint)
def inTolerance(self, tolerance, temp, setPoint):
if temp > (setPoint + tolerance) or temp < (setPoint - tolerance):
self.lcdNumber.setStyleSheet("background-color: rgb(255, 0, 0);")
if not self.elapsedTimer.isValid():
# the timer has not been started or has been invalidated
self.elapsedTimer.start()
elif self.elapsedTimer.elapsed() > 10000:
# ten seconds have passed, send the email
emailer(self.emailList, 'Test Oven', temp, setPoint)
# restart the timer, otherwise another mail could possibly be
# sent again the next cycle
self.elapsedTimer.start()
# in any other case, the elapsed time is less than the limit, just
# go on
else:
# temperature is within tolerance, invalidate the timer so that it can
# be restarted when necessary
self.elapsedTimer.invalidate()
self.lcdNumber.setStyleSheet("background-color: rgb(255, 255, 255);")
if __name__ == "__main__":
import sys
sys_argv = sys.argv
sys_argv += ['--style', 'Fusion']
app = QtWidgets.QApplication(sys_argv)
window = Window()
window.show()
sys.exit(app.exec_())
As said, I'm using a QWidget class.
It seems like you're using the output of the pyuic utility to create your program, which is something you should never do. You should create your program in a separate script, and use that generated file as an imported module. The py file created from pyuic should NEVER be edited.
In this case I created the interface completely from the code, but you can still recreate your ui in designer and use the generated py file as explained in the documentation (the third method, multiple inheritance approach, is usually the best).

Background color a specific table row given row number for QAbstractTableModel in PyQt5

In PyQt5, I am using the model view to display a table. The model is the QAbstractTableModel, and I want to background color say row 0. The coloring works, but all rows get colored, instead of the row that I specified. Also, when I change to Qt.Background role, I get some "tickbox" in my cell that I don't want. I guess, that it is my understanding of what actually happen in QAbstractTableModel's def data part that prevents me from achieve the desired effect.
This is my code snippet part as I have already tried. Note the status 1 and status 2 are actually True or False in my case. If True, this entire row should be colored as background green, else it should stay white.
#Make some dummy data
tabledata = list()
tabledata.append(('item 1', 'amount 1', 'price 1', 'status 1'))
tabledata.append(('item 2', 'amount 2', 'price 2', 'status 2'))
#The self.model below is QAbstractTableModel subclassed
self.model.modelTableData = tabledata
#try set data for just one cell
self.model.setData(self.model.index(0,0), QtCore.Qt.BackgroundRole)
self.model.layoutChanged.emit()
Then in my QAbstractTableModel class, I have the following in def data
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
#inhert from QAbstractTableModel
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
def rowCount(self, parent):
return len(self.modelTableData)
def columnCount(self, parent):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.BackgroundRole:
print('Qt.BackgroundRole at ' + str(index.row()))
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
print('Not Qt.BackgroundRole at ' + str(index.row()))
return self.modelTableData[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
I have googled on similar examples and studied this one in particular
https://python-forum.io/Thread-Change-color-of-a-row-of-a-QTableView
What they seems to do is
if role == QtCore.Qt.BackgroundRole and "something more":
#then do something
It is this "something more" that I don't know how to parse into the def data method. Ideally it should be my row data status 1 that either can be True or False, but my understanding is that def data part is actually returning the data for the viewer?
Also, I get confused about that in my code, when I executed the print, it seems that even though I stated in my data that only one cell at QModelIndex (0,0) is set to green, the next row is also set to green. What is the reason for this behaviour?
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_v00.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import POSTools as tool
import json
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1680, 1050)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.cb_OrderList = QtWidgets.QComboBox(self.centralwidget)
self.cb_OrderList.setGeometry(QtCore.QRect(160, 30, 111, 31))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(2)
sizePolicy.setHeightForWidth(self.cb_OrderList.sizePolicy().hasHeightForWidth())
self.cb_OrderList.setSizePolicy(sizePolicy)
self.cb_OrderList.setObjectName("cb_OrderList")
self.le_NewTable = QtWidgets.QLineEdit(self.centralwidget)
self.le_NewTable.setGeometry(QtCore.QRect(30, 30, 113, 35))
self.le_NewTable.setObjectName("le_NewTable")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(30, 10, 60, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(170, 10, 60, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.le_ItemName = QtWidgets.QLineEdit(self.centralwidget)
self.le_ItemName.setGeometry(QtCore.QRect(30, 100, 171, 35))
self.le_ItemName.setObjectName("le_ItemName")
self.le_ItemAmount = QtWidgets.QLineEdit(self.centralwidget)
self.le_ItemAmount.setGeometry(QtCore.QRect(220, 100, 113, 35))
self.le_ItemAmount.setObjectName("le_ItemAmount")
self.le_UnitPrice = QtWidgets.QLineEdit(self.centralwidget)
self.le_UnitPrice.setGeometry(QtCore.QRect(350, 100, 113, 35))
self.le_UnitPrice.setObjectName("le_UnitPrice")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(30, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(220, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(350, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(480, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.tableView = QtWidgets.QTableView(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(30, 150, 711, 461))
self.tableView.setObjectName("tableView")
self.pb_remove = QtWidgets.QPushButton(self.centralwidget)
self.pb_remove.setGeometry(QtCore.QRect(750, 250, 151, 101))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.pb_remove.setFont(font)
self.pb_remove.setObjectName("pb_remove")
self.pb_receipt = QtWidgets.QPushButton(self.centralwidget)
self.pb_receipt.setGeometry(QtCore.QRect(590, 620, 151, 101))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.pb_receipt.setFont(font)
self.pb_receipt.setObjectName("pb_receipt")
self.label_TotalPrice = QtWidgets.QLabel(self.centralwidget)
self.label_TotalPrice.setGeometry(QtCore.QRect(480, 100, 121, 35))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.label_TotalPrice.setFont(font)
self.label_TotalPrice.setObjectName("label_TotalPrice")
self.le_Discount = QtWidgets.QLineEdit(self.centralwidget)
self.le_Discount.setGeometry(QtCore.QRect(610, 100, 131, 35))
self.le_Discount.setObjectName("le_Discount")
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setGeometry(QtCore.QRect(610, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_7.setFont(font)
self.label_7.setObjectName("label_7")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(750, 150, 151, 101))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1680, 22))
self.menubar.setObjectName("menubar")
self.menuMore_Options = QtWidgets.QMenu(self.menubar)
self.menuMore_Options.setObjectName("menuMore_Options")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionCount_Up = QtWidgets.QAction(MainWindow)
self.actionCount_Up.setObjectName("actionCount_Up")
self.menuMore_Options.addSeparator()
self.menuMore_Options.addAction(self.actionCount_Up)
self.menubar.addAction(self.menuMore_Options.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.le_NewTable, self.cb_OrderList)
MainWindow.setTabOrder(self.cb_OrderList, self.le_ItemName)
MainWindow.setTabOrder(self.le_ItemName, self.le_ItemAmount)
MainWindow.setTabOrder(self.le_ItemAmount, self.le_UnitPrice)
MainWindow.setTabOrder(self.le_UnitPrice, self.le_Discount)
MainWindow.setTabOrder(self.le_Discount, self.pushButton)
MainWindow.setTabOrder(self.pushButton, self.pb_remove)
MainWindow.setTabOrder(self.pb_remove, self.pb_receipt)
MainWindow.setTabOrder(self.pb_receipt, self.tableView)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Order"))
self.label_2.setText(_translate("MainWindow", "Order List"))
self.label_3.setText(_translate("MainWindow", "Item Name"))
self.label_4.setText(_translate("MainWindow", "Item Amount"))
self.label_5.setText(_translate("MainWindow", "Unit Price"))
self.label_6.setText(_translate("MainWindow", "Price"))
self.pb_remove.setText(_translate("MainWindow", "Remove"))
self.pb_receipt.setText(_translate("MainWindow", "Receipt"))
self.label_TotalPrice.setText(_translate("MainWindow", "0"))
self.label_7.setText(_translate("MainWindow", "Discount [%]"))
self.pushButton.setText(_translate("MainWindow", "Print Kitchen"))
self.menuMore_Options.setTitle(_translate("MainWindow", "More Options"))
self.actionCount_Up.setText(_translate("MainWindow", "Count Up"))
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.setupUi(self)
#Start by reading in the menu items
self.URL_MenuDB = "somewhere"
self.path_OrderDB = "somewhere"
header, menudb = tool.load_MenuDB(self.URL_MenuDB)
self.MenuHeader = header
#Prepare the completer by first creating the model
self.completermodel = QtGui.QStandardItemModel()
for item in menudb:
row = list()
for col in item:
cell = QtGui.QStandardItem(str(col))
row.append(cell)
self.completermodel.appendRow(row)
self.completer = QtWidgets.QCompleter()
self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.completer.setCompletionColumn(0)
self.completer.setModel(self.completermodel)
self.completer.setFilterMode(QtCore.Qt.MatchContains)
self.completer.activated[QtCore.QModelIndex].connect(self.onActivated)
self.le_ItemName.setCompleter(self.completer)
#Setup model view
self.TableViewHeader = ['Item', 'Qty', 'Price', 'Print status']
self.TableData = list()
self.model = TableModel(self, header = self.TableViewHeader, tabledata = self.TableData)
self.model.layoutChanged.emit()
self.tableView.setModel(self.model)
#Upon program starts up, check if OrderDB.txt exists
status, AllTables = tool.importOrderDB(self.path_OrderDB)
if status is True: #OrderDB.txt exists
#check if there is incomplete orders
self.AllTables = AllTables
#A list of all active tables
tablenames = tool.getincompleteOrder(AllTables)
if tablenames:
#update the list of tablenames into drop down list
self.cb_OrderList.clear()
self.cb_OrderList.addItems(tablenames)
#get the index of the current active tablename
self.cb_OrderList.currentText()
#Define what happens when the user press enter og return for item amount
self.le_ItemAmount.returnPressed.connect(self.ItemAmountEnterKeyPress)
#If enter is pressed at unit price, it also connects with self.ItemAmountEnterKeyPress
self.le_UnitPrice.returnPressed.connect(self.ItemAmountEnterKeyPress)
#Define what happens when input table edit field is activated
self.le_NewTable.returnPressed.connect(self.input_newTable)
def input_newTable(self): #When the user create a new order
if not self.le_NewTable.text():
return
else:
#check if OrderDB already exists, if not one will be created. If exists is True, AllTables will be returned
status, AllTables, tablename, nameclash = tool.ExistOrderDB(self.path_OrderDB, self.le_NewTable.text().strip())
if nameclash is True:
tool.msgbox(self,'Bord navn eksisterer. Valg et nyt!')
self.le_NewTable.clear()
return
if status is False: #OrderDB.txt has just been created, and AllTables containing the tableName is returned
self.AllTables = AllTables
#Sort all the incomplete tables from All Tables and return the sorted tablename as pandas DataFrame
tablename = tool.getincompleteOrder(AllTables)
#insert the tablename as list to drop down list
self.cb_OrderList.clear()
self.cb_OrderList.addItems(tablename)
self.le_NewTable.clear()
else: #OrderDB.txt exists, continue to create the new table
#create the tabledict
tabledict = tool.CreateTableDict(self.le_NewTable.text())
self.AllTables.append(tabledict)
#save to data base
tool.saveOrderDB(self.path_OrderDB, self.AllTables)
tablename = tabledict["Name"]
#get a list of all incomplete order names
ordernames = tool.getincompleteOrder(self.AllTables)
self.cb_OrderList.clear()
self.cb_OrderList.addItems(ordernames)
index = self.cb_OrderList.findText(tablename, QtCore.Qt.MatchFixedString)
#set the drop down list to the current active index
self.cb_OrderList.setCurrentIndex(index)
#Set focus to item field
self.le_ItemName.setFocus()
self.le_NewTable.clear()
def ItemAmountEnterKeyPress(self): #insert the item into the table and update the data base behind the scene
if not self.cb_OrderList.currentText():
tool.msgbox(self, 'Select an order first')
return
else:
#Update the selected item into the AllTable
#Do a match to see if self.selected matches the fields
inputtext = self.le_ItemName.text()
if inputtext.strip() == self.selected[0]:
#the selected is the same as what appears in the field. Check the remaining fields
qty = tool.isfloat(self.le_ItemAmount.text())
price = tool.isfloat(self.le_UnitPrice.text())
if qty is not False and price is not False:
#submit the fields to be input into the modelview
index = tool.getTableDict(self)
#Do the visualization
price = [item for item in self.AllTables[index]["orderPrice"]]
totalprice = sum(price)
self.TableData = list(
zip(self.AllTables[index]['itemName'],
self.AllTables[index]['orderQty'],
price,
self.AllTables[index]['PrintStatus_send2kitchen']
))
#Update into the model
tabledata = list()
tabledata.append(('item 1', 'amount 1', 'price 1', 'status 1'))
tabledata.append(('item 2', 'amount 2', 'price 2', 'status 2'))
self.model.modelTableData = tabledata
#self.model.modelTableData = self.TableData
#try set data for just one cell
self.model.setData(self.model.index(0,0),
QtCore.Qt.BackgroundRole)
self.model.layoutChanged.emit()
#tool.plotTable(self, totalprice)
#clear
self.clearInputFields()
self.le_ItemName.setFocus()
else: #the item in the fields is different from self.selected, ask the user to try again
tool.msgbox(self, 'Item er ikke korrekt valgt, prøv igen.')
self.clearInputFields(self)
self.le_ItemName.setFocus()
return
else: #User has not selected from the list
tool.msgbox(self,'Prøv igen. Du skal vælge fra listen når du indsætter item')
self.clearInputFields(self)
self.le_ItemName.setFocus()
return
def clearInputFields(self):
self.le_ItemName.clear()
self.le_ItemAmount.clear()
self.le_UnitPrice.clear()
#QtCore.pyqtSlot(QtCore.QModelIndex)
def onActivated(self, index):
self.selected = list()
for i in range(0, len(self.MenuHeader) +1):
self.selected.append(index.sibling(index.row(),i).data())
#display the selected item in the editfield
self.le_UnitPrice.setText(self.selected[3])
#change focus to amount
self.le_ItemAmount.setFocus()
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
#inhert from QAbstractTableModel
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
def rowCount(self, parent):
return len(self.modelTableData)
def columnCount(self, parent):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.BackgroundRole:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
return self.modelTableData[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The expected outcome is only the specified row get colored. Also, the tick mark at each cell that I assume is related to Qt.Background is removed.
Thanks!
The logic of the data() method is to filter the information, in this case I will use a dictionary also considering that you want the complete row to be painted then save a QPersistentModel associated to the chosen row but to column 0, finally the method setData() does nothing by default so you have to override.
The error that indicates about the checkboxes is because you are returning the text for any other role like the Qt::CheckStateRole, instead you must filter the information as I already indicated
from PyQt5 import QtCore, QtGui, QtWidgets
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
self.background_colors = dict()
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.modelTableData)
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if (
0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()
):
if role == QtCore.Qt.BackgroundRole:
ix = self.index(index.row(), 0)
pix = QtCore.QPersistentModelIndex(ix)
if pix in self.background_colors:
color = self.background_colors[pix]
return color
elif role == QtCore.Qt.DisplayRole:
return self.modelTableData[index.row()][index.column()]
def setData(self, index, value, role):
if not index.isValid():
return False
if (
0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()
):
if role == QtCore.Qt.BackgroundRole and index.isValid():
ix = self.index(index.row(), 0)
pix = QtCore.QPersistentModelIndex(ix)
self.background_colors[pix] = value
return True
return False
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QTableView()
header = ["Item", "Qty", "Price", "Print status"]
tabledata = [
("item 1", "amount 1", "price 1", "status 1"),
("item 2", "amount 2", "price 2", "status 2"),
]
model = TableModel(None, header, tabledata)
model.setData(
model.index(0, 0), QtGui.QColor(QtCore.Qt.green), QtCore.Qt.BackgroundRole
)
w.setModel(model)
w.show()
sys.exit(app.exec_())
#eyllanesc thanks so much for giving me another opportunity to learn. It helped by realizing that I need to filter the information. Also, I realized that I actually don't need to setData for this to work. Below is how I have rewritten the code based on your comments and example. I have only one question left, the way I implemented the def data below, doesn't it make the code very expensive, in the sense that the enumerator loop needs to be executed for identifying which rows need to be colored every time the def data is called?
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
#inhert from QAbstractTableModel
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
def rowCount(self, parent):
return len(self.modelTableData)
def columnCount(self, parent):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.CheckStateRole:
return None
#get rows to be colored
rowscolor = list()
for item in enumerate(self.modelTableData):
if item[1][-1] == False:
rowscolor.append(item[0])
if role == QtCore.Qt.BackgroundRole and index.row() in rowscolor:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
return self.modelTableData[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None

How to properly connect two functions in python?

I have problem with connecting two functions to each other in my small program.
I am using PyQt5 and PyPDF2 modules.I would like to link two pdf files into one.
In my program I have 3 buttons:
btnPlik1 - browse 1st file (connected to function openFile1)
btnPlik2 - browse 2nd file (connected to function openFile2)
btnPlik3 - 'start' - run program (connected to function laczeniePdf)
Functions work separately but when I would like to connect them by clicking 'Start'(btnPlik3) my program crashes. Below is my code:
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
g = open(pathFileName, 'rb')
return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
h = open(pathFileName, 'rb')
return h
def laczeniePdf(self,g, h):
readerLinkPage1 = PyPDF2.PdfFileReader(open(g, 'rb'))
readerLinkPage2 = PyPDF2.PdfFileReader(open(h, 'rb'))
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
I am looking forward for your hints and advises
EDIT:
Here is code of class we are talking about(it is separate window in my program)
class Ui_PolaczPliki(object):
def setupUi(self, PolaczPliki):
PolaczPliki.setObjectName("PolaczPliki")
PolaczPliki.resize(295, 113)
self.btnPlik1 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik1.setGeometry(QtCore.QRect(30, 40, 91, 41))
self.btnPlik1.setObjectName("btnPlik1")
self.btnPlik1.clicked.connect(self.openFile1)
self.btnPlik2 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik2.setGeometry(QtCore.QRect(160, 40, 91, 41))
self.btnPlik2.setObjectName("btnPlik2")
self.btnPlik2.clicked.connect(self.openFile2)
self.btnPlik3 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik3.setGeometry(QtCore.QRect(80, 80, 40, 20))
self.btnPlik3.setObjectName("btnPlik3")
self.btnPlik3.clicked.connect(self.laczeniePdf)
self.label = QtWidgets.QLabel(PolaczPliki)
self.label.setGeometry(QtCore.QRect(50, 10, 47, 13))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(PolaczPliki)
self.label_2.setGeometry(QtCore.QRect(180, 10, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(PolaczPliki)
QtCore.QMetaObject.connectSlotsByName(PolaczPliki)
def retranslateUi(self, PolaczPliki):
_translate = QtCore.QCoreApplication.translate
PolaczPliki.setWindowTitle(_translate("PolaczPliki", "Polacz pliki"))
self.btnPlik1.setText(_translate("PolaczPliki", "Dodaj"))
self.btnPlik2.setText(_translate("PolaczPliki", "Dodaj"))
self.btnPlik3.setText(_translate("PolaczPliki", "Start"))
self.label.setText(_translate("PolaczPliki", "Plik nr 1"))
self.label_2.setText(_translate("PolaczPliki", "Plik nr 2"))
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
g = open(pathFileName, 'rb')
return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
h = open(pathFileName, 'rb')
return h
def laczeniePdf(self, g,h):
readerLinkPage1 = PyPDF2.PdfFileReader(g)
readerLinkPage2 = PyPDF2.PdfFileReader(h)
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_MainWindow()
w = QtWidgets.QMainWindow()
ex.setupUi(w)
w.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import PyPDF2
class Ui_PolaczPliki(object):
def __init__(self): # +++
self.file_1 = None # +++
self.file_2 = None # +++
def setupUi(self, PolaczPliki):
PolaczPliki.setObjectName("PolaczPliki")
PolaczPliki.resize(600, 150)
self.btnPlik1 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik1.setGeometry(QtCore.QRect(30, 40, 91, 41))
self.btnPlik1.setObjectName("btnPlik1")
self.btnPlik1.clicked.connect(self.openFile1)
self.btnPlik2 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik2.setGeometry(QtCore.QRect(300, 40, 91, 41))
self.btnPlik2.setObjectName("btnPlik2")
self.btnPlik2.clicked.connect(self.openFile2)
self.btnPlik3 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik3.setGeometry(QtCore.QRect(165, 90, 91, 41))
self.btnPlik3.setObjectName("btnPlik3")
self.btnPlik3.clicked.connect(lambda: self.laczeniePdf(self.file_1, self.file_2)) # +++
self.label = QtWidgets.QLabel(PolaczPliki)
self.label.setGeometry(QtCore.QRect(30, 10, 47, 13))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(PolaczPliki)
self.label_2.setGeometry(QtCore.QRect(300, 10, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(PolaczPliki)
QtCore.QMetaObject.connectSlotsByName(PolaczPliki)
def retranslateUi(self, PolaczPliki):
_translate = QtCore.QCoreApplication.translate
PolaczPliki.setWindowTitle(_translate("PolaczPliki", "Polacz pliki"))
self.btnPlik1.setText(_translate("PolaczPliki", "Dodaj Plik nr 1"))
self.btnPlik2.setText(_translate("PolaczPliki", "Dodaj Plik nr 2"))
self.btnPlik3.setText(_translate("PolaczPliki", "Start"))
self.label.setText(_translate("PolaczPliki", "Plik nr 1"))
self.label_2.setText(_translate("PolaczPliki", "Plik nr 2"))
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("\nWybrany plik: ", pathFileName)
self.file_1 = pathFileName # +++
self.label.setText("{}".format(self.file_1)) # +++
self.label.adjustSize() # +++
#g = open(pathFileName, 'rb')
#print("\ng = open(pathFileName, 'rb') =`{}`, \ntype g =`{}` ".format(g, type(g)))
#return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("\nWybrany plik: ", pathFileName)
self.file_2 = pathFileName # +++
self.label_2.setText("{}".format(self.file_2)) # +++
self.label_2.adjustSize() # +++
#h = open(pathFileName, 'rb')
#print("\nh = open(pathFileName, 'rb') =`{}`, \ntype h =`{}` ".format(h, type(h)))
#return h
def laczeniePdf(self, file_1, file_2): # +++
g = open(file_1, 'rb') # +++
h = open(file_2, 'rb') # +++
readerLinkPage1 = PyPDF2.PdfFileReader(g)
readerLinkPage2 = PyPDF2.PdfFileReader(h)
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
print("\n g=`{}` + h=`{}` !!!".format(file_1, file_2))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_PolaczPliki() #Ui_MainWindow() # +++
w = QtWidgets.QMainWindow()
ex.setupUi(w)
w.show()
sys.exit(app.exec_())

pyqt QObject: Cannot create children for a parent that is in a different thread

QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x9919018), parent's thread is QThread(0x97331e0), current thread is flooderthread(0x97b4c10)
error means ? am sorry because am new to pyqt
here is the code :
i know the code is finished yet but it should work i guess the problem is with myfun.log function...
#! /usr/bin/python
# -*- coding: utf-8 -*-
import urllib, urllib2, itertools, threading, cookielib, Cookie, sys, time, hashlib, os
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
gui=QtGui.QApplication.processEvents
texttoset=""
class fun():
global texttoset
def checkpassword(self):
if ui.passwordcheck.isChecked()==True:
return 1
else :
return 0
def log(self, text):
if text != False:
firsttext=str(ui.console.toPlainText())
secondtext=firsttext+text+"\n"
ui.console.setText(secondtext)
log=open("log.log", "a")
log.write(text+"\n")
log.close()
else :
firsttext=str(ui.console.toPlainText())
secondtext=firsttext+texttoset+"\n"
ui.console.setText(secondtext)
log=open("log.log", "a")
log.write(texttoset+"\n")
log.close()
def disable(self):
MainWindow.setEnabled(False)
pass
def enable(self):
MainWindow.setEnabled(True)
pass
def checkmethod(self):
if ui.get.isChecked()==True:
return 1
elif ui.post.isChecked()==True:
return 2
else :
return 0
def main(self):
connecter()
gui()
f1.start()
gui()
time.sleep(3)
gui()
f2.start()
gui()
time.sleep(3)
gui()
f3.start()
gui()
time.sleep(3)
gui()
f4.start()
gui()
time.sleep(3)
gui()
f5.start()
gui()
self.sleep(3)
gui()
f6.start()
gui()
def killer(self):
f1.terminate()
f2.terminate()
f3.terminate()
f4.terminate()
f5.terminate()
f6.terminate()
def close(self):
self.killer()
os.abort()
sys.exit()
myfun=fun()
def connecter():
QtCore.QObject.connect(f1, QtCore.SIGNAL("log(bool)"), myfun.log)
QtCore.QObject.connect(f1, QtCore.SIGNAL("enable()"), myfun.enable)
QtCore.QObject.connect(f1, QtCore.SIGNAL("disable()"), myfun.disable)
QtCore.QObject.connect(f2, QtCore.SIGNAL("log(bool)"), myfun.log)
QtCore.QObject.connect(f2, QtCore.SIGNAL("enable()"), myfun.enable)
QtCore.QObject.connect(f2, QtCore.SIGNAL("disable()"), myfun.disable)
QtCore.QObject.connect(f3, QtCore.SIGNAL("log(bool)"), myfun.log)
QtCore.QObject.connect(f3, QtCore.SIGNAL("enable()"), myfun.enable)
QtCore.QObject.connect(f3, QtCore.SIGNAL("disable()"), myfun.disable)
QtCore.QObject.connect(f4, QtCore.SIGNAL("log(bool)"), myfun.log)
QtCore.QObject.connect(f4, QtCore.SIGNAL("enable()"), myfun.enable)
QtCore.QObject.connect(f4, QtCore.SIGNAL("disable()"), myfun.disable)
QtCore.QObject.connect(f5, QtCore.SIGNAL("log(bool)"), myfun.log)
QtCore.QObject.connect(f5, QtCore.SIGNAL("enable()"), myfun.enable)
QtCore.QObject.connect(f5, QtCore.SIGNAL("disable()"), myfun.disable)
QtCore.QObject.connect(f6, QtCore.SIGNAL("log(bool)"), myfun.log)
QtCore.QObject.connect(f6, QtCore.SIGNAL("enable()"), myfun.enable)
QtCore.QObject.connect(f6, QtCore.SIGNAL("disable()"), myfun.disable)
x=0
num=0
class flooderthread(QtCore.QThread):
global texttoset
def __init__(self, x, num):
QtCore.QThread.__init__(self)
self.x=x
self.num=num
def log(self, text):
texttolog=str(text)
time.sleep(1)
self.emit(QtCore.SIGNAL("log(bool)"), False)
time.sleep(2)
def enable(self):
time.sleep(1)
self.emit(QtCore.SIGNAL("enable()"))
def disable(self):
time.sleep(1)
self.emit(QtCore.SIGNAL("disable()"))
def run(self):
connecter()
self.log("\n\n--------------------------------------------------new session-------------------------------------\n\n")
itered=False
gui()
self.disable()
gui()
self.log("setting params...")
param={ui.dataname1.text():ui.datavalue1.text(),ui.dataname3.text():ui.datavalue3.text(),ui.dataname3.text():ui.datavalue3.text(), }
self.log("checking password...")
if myfun.checkpassword()==1:
itered=True
self.log("password is true")
else :
self.log("password is null ")
self.log("itered operation")
self.log("setting url")
url=str(ui.url.text())
if url[:4]!="http" and url[:3]!="ftp":
self.log("url error exiting the whole function")
self.log("please set a valide protocole!!")
gui()
self.enable()
gui()
return 1
pass
else :
self.log("valid url")
gui()
self.log("url is "+url)
self.log("setting proxy")
proxy="http://"+ui.proxyuser.text()+":"+ui.proxypass.text()+"#"+ui.proxyhost.text()+":"+ui.proxyport.text()
self.log("proxy is "+proxy)
gui()
self.log("preparing params...")
urlparam=urllib.urlencode(param)
gui()
self.log("params are "+urlparam)
self.log("setting up headers...")
header={'User-Agent':str(ui.useragent.toPlainText())}
self.log("headers are "+ str(header))
self.log("setting up proxy handler..")
proxyhandler=urllib2.ProxyHandler({"http":str(proxy)})
self.log("checking method")
if myfun.checkmethod()==1:
self.log("method is get..")
self.log("setting request..")
finalurl=url+urlparam
gui()
self.log("final url is"+finalurl)
req=urllib2.Request(finalurl, None, headers)
elif myfun.checkmethod()==2:
self.log("method is post...")
self.log("setting request..")
finalurl=url
gui()
self.log("final url is "+finalurl)
req=urllib2.Request(finalurl, urlparam, header)
else :
self.log("error has been accourded")
self.log("please select a method!!")
gui()
self.log("exiting the whole functions")
gui()
self.enable()
return 1
pass
self.log("intilizing cookies..")
c1=Cookie.SimpleCookie()
c1[str(ui.cookiename1.text())]=str(ui.cookievalue1.text())
c1[str(ui.cookiename1.text())]['path']='/'
c1[str(ui.cookiename2.text())]=str(ui.cookievalue2.text())
c1[str(ui.cookiename2.text())]['path']='/'
c1[str(ui.cookiename3.text())]=str(ui.cookievalue3.text())
c1[str(ui.cookiename3.text())]['domain']=url
c1[str(ui.cookiename3.text())]['path']='/'
c1[str(ui.cookiename4.text())]=str(ui.cookievalue4.text())
c1[str(ui.cookiename4.text())]['domain']=url
c1[str(ui.cookiename4.text())]['path']='/'
self.log("cookies are.. :"+str(c1))
cj=cookielib.CookieJar()
cj.set_cookie(c1)
opener = urllib2.build_opener(proxyhandler, urllib2.HTTPCookieProcessor(cj))
self.log("insatlling opener")
urllib2.install_opener(opener)
self.log("setting the two operations....")
if itered==Fasle:
self.log("starting the flooding loop")
gui()
while true:
try:
gui()
opener.open(req)
except e:
self.log("error connecting : "+e.reason)
self.log("will continue....")
continue
gui()
elif itered==True:
pass
f1=flooderthread(1, 1)
f2=flooderthread(2, 2)
f3=flooderthread(3, 3)
f4=flooderthread(4, 4)
f5=flooderthread(5, 5)
f6=flooderthread(6, 6)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.setMinimumSize(QtCore.QSize(838, 500))
MainWindow.setMaximumSize(QtCore.QSize(838, 500))
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "memo flooder", None, QtGui.QApplication.UnicodeUTF8))
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.console=QtGui.QTextEdit(self.centralwidget)
self.console.setGeometry(10, 350, 800,130)
self.console.setReadOnly(True)
self.console.setObjectName("console")
self.groupBox = QtGui.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(30, 50, 71, 80))
self.groupBox.setTitle(QtGui.QApplication.translate("MainWindow", "method:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.post = QtGui.QRadioButton(self.groupBox)
self.post.setGeometry(QtCore.QRect(10, 20, 61, 22))
self.post.setText(QtGui.QApplication.translate("MainWindow", "post", None, QtGui.QApplication.UnicodeUTF8))
self.post.setChecked(True)
self.post.setObjectName(_fromUtf8("post"))
self.get = QtGui.QRadioButton(self.groupBox)
self.get.setGeometry(QtCore.QRect(10, 50, 51, 22))
self.get.setText(QtGui.QApplication.translate("MainWindow", "get", None, QtGui.QApplication.UnicodeUTF8))
self.get.setObjectName(_fromUtf8("get"))
self.url = QtGui.QLineEdit(self.centralwidget)
self.url.setGeometry(QtCore.QRect(70, 20, 671, 27))
self.url.setInputMethodHints(QtCore.Qt.ImhUrlCharactersOnly)
self.url.setObjectName(_fromUtf8("url"))
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
self.groupBox_2.setGeometry(QtCore.QRect(110, 50, 371, 111))
self.groupBox_2.setTitle(QtGui.QApplication.translate("MainWindow", "data:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.dataname1 = QtGui.QLineEdit(self.groupBox_2)
self.dataname1.setGeometry(QtCore.QRect(20, 30, 101, 27))
self.dataname1.setObjectName(_fromUtf8("dataname1"))
self.label = QtGui.QLabel(self.groupBox_2)
self.label.setGeometry(QtCore.QRect(40, 10, 67, 17))
self.label.setText(QtGui.QApplication.translate("MainWindow", "name:", None, QtGui.QApplication.UnicodeUTF8))
self.label.setObjectName(_fromUtf8("label"))
self.dataname2 = QtGui.QLineEdit(self.groupBox_2)
self.dataname2.setGeometry(QtCore.QRect(130, 30, 113, 27))
self.dataname2.setObjectName(_fromUtf8("dataname2"))
self.dataname3 = QtGui.QLineEdit(self.groupBox_2)
self.dataname3.setGeometry(QtCore.QRect(250, 30, 113, 27))
self.dataname3.setObjectName(_fromUtf8("dataname3"))
self.label_2 = QtGui.QLabel(self.groupBox_2)
self.label_2.setGeometry(QtCore.QRect(40, 60, 67, 17))
self.label_2.setText(QtGui.QApplication.translate("MainWindow", "value:", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.datavalue1 = QtGui.QLineEdit(self.groupBox_2)
self.datavalue1.setGeometry(QtCore.QRect(20, 80, 101, 27))
self.datavalue1.setObjectName(_fromUtf8("datavalue1"))
self.datavalue2 = QtGui.QLineEdit(self.groupBox_2)
self.datavalue2.setGeometry(QtCore.QRect(130, 80, 113, 27))
self.datavalue2.setObjectName(_fromUtf8("datavalue2"))
self.datavalue3 = QtGui.QLineEdit(self.groupBox_2)
self.datavalue3.setGeometry(QtCore.QRect(250, 80, 113, 27))
self.datavalue3.setObjectName(_fromUtf8("datavalue3"))
self.groupBox_4 = QtGui.QGroupBox(self.centralwidget)
self.groupBox_4.setGeometry(QtCore.QRect(670, 50, 151, 111))
self.groupBox_4.setTitle(QtGui.QApplication.translate("MainWindow", "password:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_4.setObjectName(_fromUtf8("groupBox_4"))
self.passname = QtGui.QLineEdit(self.groupBox_4)
self.passname.setGeometry(QtCore.QRect(10, 30, 113, 27))
self.passname.setObjectName(_fromUtf8("passname"))
self.passvalue = QtGui.QLineEdit(self.groupBox_4)
self.passvalue.setGeometry(QtCore.QRect(10, 80, 113, 27))
self.passvalue.setObjectName(_fromUtf8("passvalue"))
self.passwordcheck = QtGui.QCheckBox(self.centralwidget)
self.passwordcheck.setGeometry(QtCore.QRect(670, 180, 97, 22))
self.passwordcheck.setText(QtGui.QApplication.translate("MainWindow", "password", None, QtGui.QApplication.UnicodeUTF8))
self.passwordcheck.setChecked(True)
self.passwordcheck.setObjectName(_fromUtf8("passwordcheck"))
self.groupBox_5 = QtGui.QGroupBox(self.centralwidget)
self.groupBox_5.setGeometry(QtCore.QRect(29, 169, 441, 81))
self.groupBox_5.setTitle(QtGui.QApplication.translate("MainWindow", "proxy:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_5.setObjectName(_fromUtf8("groupBox_5"))
self.proxyhost = QtGui.QLineEdit(self.groupBox_5)
self.proxyhost.setGeometry(QtCore.QRect(20, 30, 113, 27))
self.proxyhost.setObjectName(_fromUtf8("proxyhost"))
self.proxyport = QtGui.QLineEdit(self.groupBox_5)
self.proxyport.setGeometry(QtCore.QRect(140, 30, 51, 27))
self.proxyport.setInputMethodHints(QtCore.Qt.ImhDigitsOnly|QtCore.Qt.ImhPreferNumbers)
self.proxyport.setObjectName(_fromUtf8("proxyport"))
self.proxyuser = QtGui.QLineEdit(self.groupBox_5)
self.proxyuser.setGeometry(QtCore.QRect(200, 30, 113, 27))
self.proxyuser.setObjectName(_fromUtf8("proxyuser"))
self.proxypass = QtGui.QLineEdit(self.groupBox_5)
self.proxypass.setGeometry(QtCore.QRect(320, 30, 113, 27))
self.proxypass.setObjectName(_fromUtf8("proxypass"))
self.label_4 = QtGui.QLabel(self.groupBox_5)
self.label_4.setGeometry(QtCore.QRect(100, 10, 67, 17))
self.label_4.setText(QtGui.QApplication.translate("MainWindow", "host", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(self.groupBox_5)
self.label_5.setGeometry(QtCore.QRect(150, 10, 67, 17))
self.label_5.setText(QtGui.QApplication.translate("MainWindow", "port", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setObjectName(_fromUtf8("label_5"))
self.label_6 = QtGui.QLabel(self.groupBox_5)
self.label_6.setGeometry(QtCore.QRect(200, 10, 67, 17))
self.label_6.setText(QtGui.QApplication.translate("MainWindow", "username", None, QtGui.QApplication.UnicodeUTF8))
self.label_6.setObjectName(_fromUtf8("label_6"))
self.label_7 = QtGui.QLabel(self.groupBox_5)
self.label_7.setGeometry(QtCore.QRect(320, 10, 67, 17))
self.label_7.setText(QtGui.QApplication.translate("MainWindow", "password", None, QtGui.QApplication.UnicodeUTF8))
self.label_7.setObjectName(_fromUtf8("label_7"))
self.groupBox_6 = QtGui.QGroupBox(self.centralwidget)
self.groupBox_6.setGeometry(QtCore.QRect(30, 260, 531, 91))
self.groupBox_6.setTitle(QtGui.QApplication.translate("MainWindow", "cookies:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_6.setObjectName(_fromUtf8("groupBox_6"))
self.cookiename1 = QtGui.QLineEdit(self.groupBox_6)
self.cookiename1.setGeometry(QtCore.QRect(10, 20, 113, 27))
self.cookiename1.setObjectName(_fromUtf8("cookiename1"))
self.cookiename2 = QtGui.QLineEdit(self.groupBox_6)
self.cookiename2.setGeometry(QtCore.QRect(140, 20, 113, 27))
self.cookiename2.setObjectName(_fromUtf8("cookename2"))
self.cookiename3 = QtGui.QLineEdit(self.groupBox_6)
self.cookiename3.setGeometry(QtCore.QRect(270, 20, 113, 27))
self.cookiename3.setObjectName(_fromUtf8("cookiename3"))
self.cookiename4 = QtGui.QLineEdit(self.groupBox_6)
self.cookiename4.setGeometry(QtCore.QRect(390, 20, 113, 27))
self.cookiename4.setObjectName(_fromUtf8("cookiename4"))
self.cookievalue1 = QtGui.QLineEdit(self.groupBox_6)
self.cookievalue1.setGeometry(QtCore.QRect(10, 50, 113, 27))
self.cookievalue1.setObjectName(_fromUtf8("cookievalue1"))
self.cookievalue2 = QtGui.QLineEdit(self.groupBox_6)
self.cookievalue2.setGeometry(QtCore.QRect(140, 50, 113, 27))
self.cookievalue2.setObjectName(_fromUtf8("cookievalue2"))
self.cookievalue3 = QtGui.QLineEdit(self.groupBox_6)
self.cookievalue3.setGeometry(QtCore.QRect(270, 50, 113, 27))
self.cookievalue3.setObjectName(_fromUtf8("cookievalue3"))
self.cookievalue4 = QtGui.QLineEdit(self.groupBox_6)
self.cookievalue4.setGeometry(QtCore.QRect(390, 50, 113, 27))
self.cookievalue4.setObjectName(_fromUtf8("cookievalue4"))
self.groupBox_7 = QtGui.QGroupBox(self.centralwidget)
self.groupBox_7.setGeometry(QtCore.QRect(570, 260, 251, 80))
self.groupBox_7.setTitle(QtGui.QApplication.translate("MainWindow", "useragents:", None, QtGui.QApplication.UnicodeUTF8))
self.groupBox_7.setObjectName(_fromUtf8("groupBox_7"))
self.useragent = QtGui.QTextEdit(self.groupBox_7)
self.useragent.setGeometry(QtCore.QRect(10, 20, 211, 51))
self.useragent.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.useragent.setObjectName(_fromUtf8("useragent"))
self.start = QtGui.QPushButton(self.centralwidget)
self.start.setGeometry(QtCore.QRect(750, 20, 71, 27))
self.start.setText(QtGui.QApplication.translate("MainWindow", "start", None, QtGui.QApplication.UnicodeUTF8))
self.start.setObjectName(_fromUtf8("start"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(30, 20, 67, 17))
self.label_3.setText(QtGui.QApplication.translate("MainWindow", "url :", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setObjectName(_fromUtf8("label_3"))
MainWindow.setCentralWidget(self.centralwidget)
QtCore.QObject.connect(self.start, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), myfun.main)
QtCore.QObject.connect(self.passwordcheck, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.groupBox_4.setEnabled)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def __del__():
myfun.killer()
os.abort()
sys.exit()
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
myfun.log("\n\n--------------------------------------------------new session-------------------------------------\n\n")
MainWindow.show()
sys.exit(app.exec_())
I have almost no idea whats going on in your code, in terms of its intent, but here is the offending line of code causing your crash:
class flooderthread(QtCore.QThread):
...
def run(self):
connecter() # this is the culprit
In your fun.main(), you call the connecter() once already to set up all your signal/slot connections. This call is occurring in your main thread. But then you have each thread also calling that method, which is trying to make duplicate connections to objects across threads. The actual crash may be caused much deeper than this function, because its the result of signal firing, but I find it just too difficult to hop around the code to get any deeper. Most likely you are having the thread directly modify GUI elements when it shouldn't.
Once you have that fixed, you have one other typo that will make it crash:
def main(self):
connecter()
...
time.sleep(3)
gui()
f5.start()
gui()
self.sleep(3) # should be time.sleep(3)
gui()
...
Aside from this, I just want to point out that this script is extremely hard to follow. You are making use of globals everywhere, so its hard to know where certain variables and function calls were defined. You have to scroll around a bunch, chasing them down. You may want to stop and reorganize this before it continues to snowball.
I would highly suggest picking up a book like this: http://www.qtrac.eu/pyqtbook.html
What you should focus on is organizing proper classes. Your current class structures need a lot of review, so you may want to even pick up a good python book to first learn how to write classes. I realize you are just learning, which is why I am hoping this advise will help steer you in the right direction.

Categories