I'm trying to add a window to Qmdi area when user clicks a button inside another widget in Qmdi area.
Codes i have written so far is:
from __future__ import print_function
from PyQt4.QtGui import *
import csv
import subprocess
import sys
from PyQt4 import QtGui
from PyQt4.QtCore import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.lee = QLineEdit()
self.lee.setObjectName("hosta")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("inject")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.lee)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"), self.button_click)
self.setWindowTitle("Stuck-at-0")
def button_click(self):
# shost is a QString object
n = int(self.le.text())
line = str(self.lee.text())
print(n, line)
with open('main.txt', 'r') as files:
# read a list of lines into data
data = files.readlines()
# now inject fault in nth level, note that you have to add a newline
print
data[1]
if line in data[0]:
data.insert(n + 1, '0' + ',' + line + '\n')
# and write everything back
with open('main.txt', 'w') as files:
files.writelines(data)
res = subprocess.call(['python stuck.py'], shell=True)
res = subprocess.call(['python comp.py'], shell=True)
class UserWindow(QtGui.QMainWindow):
def __init__(self):
super(UserWindow, self).__init__()
self.ctr_frame = QtGui.QWidget()
self.specTable = QtGui.QTableView()
self.specModel = QtGui.QStandardItemModel(self)
self.specList = self.createSpecTable()
self.initUI()
def specData(self):
with open('tests.csv', 'rb') as csvInput:
for row in csv.reader(csvInput):
if row > 0:
items = [QtGui.QStandardItem(field) for field in row]
self.specModel.appendRow(items)
def createSpecTable(self):
# This is a test header - different from what is needed
specHdr = ['Test', 'Date', 'Time', 'Type']
self.specData()
specM = specTableModel(self.specModel, specHdr, self)
self.specTable.setModel(specM)
self.specTable.setShowGrid(False)
v_head = self.specTable.verticalHeader()
v_head.setVisible(False)
h_head = self.specTable.horizontalHeader()
h_head.setStretchLastSection(True)
self.specTable.sortByColumn(3, Qt.DescendingOrder)
return self.specTable
def initUI(self):
self.specList.setModel(self.specModel)
p_grid = QtGui.QGridLayout()
p_grid.setSpacing(5)
p_grid.addWidget(self.specList, 2, 5, 13, 50)
self.ctr_frame.setLayout(p_grid)
self.setCentralWidget(self.ctr_frame)
self.statusBar()
bar = self.menuBar()
menu_item1 = bar.addMenu("Circuit Details")
fault_inject = bar.addMenu("Fault Injection")
fault_inject_sa = fault_inject.addMenu("Stuck-at Fault")
fault_inject_sa.addAction("Stuck-at-0")
fault_inject_sa.addAction("Stuck-at-1")
fault_inject_bridge = fault_inject.addMenu("Bridging Fault")
fault_inject_bridge.addAction("Bridging-OR")
fault_inject_bridge.addAction("Bridging-AND")
fault_inject_cross = fault_inject.addMenu("Crosspoint Fault")
fault_inject_cross.addAction("Crosspoint-Appearance")
fault_inject_cross.addAction("Crosspoint-Dissappearence")
fault_inject_mgf = fault_inject.addMenu("Missing Gate Fault")
fault_inject_mgf.addAction("Single-MGF")
fault_inject_mgf.addAction("Multiple-MGF")
fault_inject_mgf.addAction("Repeated-MGF")
fault_inject_mgf.addAction("Partial-MGF")
self.setWindowTitle('Truth Table')
fault_inject.triggered[QAction].connect(self.fault_injection)
def fault_injection(self, q):
print("triggered")
if q.text() == "Stuck-at-0":
print(q.text())
exx = Form()
self.mdi.addSubWindow(exx)
exx.show()
if q.text() == "Stuck-at-1":
print(q.text())
if q.text() == "Bridging-OR":
print(q.text())
if q.text() == "Bridging-AND":
print(q.text())
if q.text() == "Crosspoint-Appearance":
print(q.text())
if q.text() == "Crosspoint-Dissappearence":
print(q.text())
if q.text() == "Single-MGF":
print(q.text())
if q.text() == "Multiple-MGF":
print(q.text())
if q.text() == "Repeated-MGF":
print(q.text())
if q.text() == "Partial-MGF":
print(q.text())
class specTableModel(QAbstractTableModel):
def __init__(self, datain, headerData, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.arrayData = datain
self.headerData = headerData
def rowCount(self, parent):
return 0
def columnCount(self, parent):
return 0
def data(self, index, role):
if not index.isValid():
return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.arraydata[index.row()][index.column()])
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.headerdata[col]
return None
class MainWindow(QMainWindow):
count = 0
filename = 0
def test_display(self,q):
self.mdi.tileSubWindows()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
menu_item1 = bar.addMenu("About Tool")
menu_item_tool = menu_item1.addMenu("User Manual")
menu_item_example = menu_item1.addMenu("Example and Demos")
menu_item2 = bar.addMenu("Reversible Computing")
menu_item_rc = menu_item2.addMenu("RC vs Conventional")
menu_item_rcg = menu_item2.addMenu("RC Gates")
menu_item_rcp = menu_item2.addMenu("Properties of RC")
menu_item_rcl = menu_item2.addMenu("RC Gate Libraries")
menu_item = bar.addMenu("Benchmark Circuits")
menu_item_gate = menu_item.addMenu("Functions")
menu_item_realize = menu_item.addMenu("Realization Library")
menu_item_nct = menu_item_realize.addMenu("NCT")
menu_item_gt = menu_item_realize.addMenu("GT")
menu_item_nctf = menu_item_realize.addMenu("NCTF")
menu_item_gf = menu_item_realize.addMenu("GF")
menu_item_4b1_5g = menu_item_gate.addMenu("4b1_5g")
menu_item_4b1_5g.addAction("4b1_5g_1")
menu_item_4b1_5g.addAction("4b1_5g_2")
menu_item_4b1_5g.addAction("4b1_5g_3")
menu_item_4b1_5g.addAction("4b1_5g_4")
menu_item_4b1_5g.addAction("4b1_5g_5")
menu_item_adder = menu_item_gate.addMenu("Adders")
menu_item_adder.addAction("1bitadder(rd32)")
menu_item_adder.addAction("5bitadder")
menu_item_adder.addAction("8bitadder")
menu_item_div_checker = menu_item_gate.addMenu("Divisiblity Checkers")
menu_item_div_checker.addAction("4mod5")
menu_item_div_checker.addAction("5mod5")
menu_item_cyclic = menu_item_gate.addMenu("Cycle Functions")
menu_item_cyclic.addAction("cycle10_2")
menu_item_cyclic.addAction("cycle17_3")
menu_item_galois = menu_item_gate.addMenu("Galois Field Multipliers")
menu_item_galois.addAction("gf2^3mult")
menu_item_galois.addAction("gf2^4mult")
menu_item_galois.addAction("gf2^5mult")
menu_item_galois.addAction("gf2^6mult")
menu_item_galois.addAction("gf2^7mult")
menu_item_galois.addAction("gf2^8mult")
menu_item_galois.addAction("gf2^9mult")
menu_item_galois.addAction("gf2^10mult")
menu_item_galois.addAction("gf2^11mult")
menu_item_galois.addAction("gf2^12mult")
menu_item_galois.addAction("gf2^13mult")
menu_item_galois.addAction("gf2^14mult")
menu_item_galois.addAction("gf2^15mult")
menu_item_galois.addAction("gf2^16mult")
menu_item_galois.addAction("gf2^17mult")
menu_item_galois.addAction("gf2^18mult")
menu_item_galois.addAction("gf2^19mult")
menu_item_galois.addAction("gf2^20mult")
menu_item_galois.addAction("gf2^32mult")
menu_item_galois.addAction("gf2^50mult")
menu_item_galois.addAction("gf2^64mult")
menu_item_galois.addAction("gf2^100mult")
menu_item_galois.addAction("gf2^127mult")
menu_item_galois.addAction("gf2^128mult")
menu_item_galois.addAction("gf2^256mult")
menu_item_galois.addAction("gf2^512mult")
menu_item_hamming = menu_item_gate.addMenu("Hamming Code Functions")
menu_item_hamming.addAction("ham3")
menu_item_hamming.addAction("ham7")
menu_item_hamming.addAction("ham15")
menu_item_hbw = menu_item_gate.addMenu("Hidden Weight Coding Functions")
menu_item_hbw.addAction("hbw4")
menu_item_hbw.addAction("hbw5")
menu_item_hbw.addAction("hbw6")
menu_item_hbw.addAction("hbw7")
menu_item_hbw.addAction("hbw8")
menu_item_hbw.addAction("hbw9")
menu_item_hbw.addAction("hbw10")
menu_item_hbw.addAction("hbw11")
menu_item_hbw.addAction("hbw12")
menu_item_hbw.addAction("hbw13")
menu_item_hbw.addAction("hbw14")
menu_item_hbw.addAction("hbw15")
menu_item_hbw.addAction("hbw16")
menu_item_hbw.addAction("hbw20")
menu_item_hbw.addAction("hbw50")
menu_item_hbw.addAction("hbw100")
menu_item_hbw.addAction("hbw200")
menu_item_hbw.addAction("hbw500")
menu_item_hbw.addAction("hbw1000")
menu_item_mdd = menu_item_gate.addMenu("MDD Worst Case")
menu_item_mdd.addAction("3_17.tfc")
menu_item_mdd.addAction("4_49")
menu_item_modular = menu_item_gate.addMenu("Modula Adders")
menu_item_modular.addAction("mod5adder")
menu_item_modular.addAction("mod1024adder")
menu_item_modular.addAction("mod1048576adder")
menu_item_prime = menu_item_gate.addMenu("N-th Prime")
menu_item_prime.addAction("nth_prime3_inc")
menu_item_prime.addAction("nth_prim4_inc")
menu_item_prime.addAction("nth_prime5_inc")
menu_item_prime.addAction("nth_prime6_inc")
menu_item_prime.addAction("nth_prime7_inc")
menu_item_prime.addAction("nth_prime8_inc")
menu_item_prime.addAction("nth_prime9_inc")
menu_item_prime.addAction("nth_prime10_inc")
menu_item_prime.addAction("nth_prime11_inc")
menu_item_prime.addAction("nth_prime12_inc")
menu_item_prime.addAction("nth_prime13_inc")
menu_item_prime.addAction("nth_prime14_inc")
menu_item_prime.addAction("nth_prime15_inc")
menu_item_prime.addAction("nth_prime16-inc")
menu_item_permanent = menu_item_gate.addMenu("Permanent")
menu_item_permanent.addAction("permanent1x1")
menu_item_permanent.addAction("permanent2x2")
menu_item_permanent.addAction("permanent3x3")
menu_item_permanent.addAction("permanent4x4")
menu_item_rd = menu_item_gate.addMenu("RD-Input Weight functions")
menu_item_rd.addAction("rd53")
menu_item_rd.addAction("rd73")
menu_item_rd.addAction("rd84")
menu_item_sym = menu_item_gate.addMenu("Symmetric Functions")
menu_item_sym.addAction("6sym")
menu_item_sym.addAction("9sym")
menu_item_oth = menu_item_gate.addMenu("Others")
menu_item_oth.addAction("2_4dec")
menu_item_oth.addAction("2of5")
menu_item_oth.addAction("xor5")
self.setWindowTitle("Reversible Fault Testing")
menu_item.triggered[QAction].connect(self.truth_table_gen)
def windowaction(self, q):
print("triggered")
print(q.text())
if "New" == "New":
MainWindow.count += 1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("tst")
self.mdi.addSubWindow(sub)
sub.show()
# truth table display widget
def truth_table_gen(self, q):
MainWindow.count += 1
MainWindow.filename = q.text()
to_readfile = open(q.text(), 'r')
try:
reading_file = to_readfile.read()
writefile = open('a.tfc', 'w')
try:
writefile.write(reading_file)
finally:
writefile.close()
finally:
to_readfile.close()
subprocess.call(['python truth_gen.py'], shell=True)
exx = UserWindow()
self.mdi.addSubWindow(exx)
exx.show()
self.mdi.tileSubWindows()
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
#ex.resize(1366, 750)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
when i click on button inside the Qmdi area widget, the code crashes.
Related
I am using following code for creating scrolling text using pyqt. Also I am creating rectangular box in my UI using QPainter. The problem is that the code as such works fine but after sometime it hangs. The message stops scrolling while other part UI is functioning. I used code from earlier stack overflow question for scrolling text Marquee effect. Following is the some part of my code
class MarqueeLabel(QtGui.QLabel):
def __init__(self, parent=None):
QtGui.QLabel.__init__(self, parent)
self.px = 0
self.py = 15
self._direction = Qt.RightToLeft #Qt.LeftToRight
self.setWordWrap(True)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update)
self.timer.start(20)
self._speed = 2
self.textLength = 0
self.fontPointSize = 0
self.setAlignment(Qt.AlignVCenter)
self.setFixedHeight(self.fontMetrics().height())
def setFont(self, font, size):
newfont = QtGui.QFont(font, size, QtGui.QFont.Bold)
QtGui.QLabel.setFont(self, newfont)
self.setFixedHeight(self.fontMetrics().height())
def updateCoordinates(self):
align = self.alignment()
if align == Qt.AlignTop:
self.py = 10
elif align == Qt.AlignBottom:
self.py = self.height() - 10
elif align == Qt.AlignVCenter:
self.py = self.height() / 2
self.fontPointSize = self.font().pointSize() / 2
self.textLength = self.fontMetrics().width(self.text())
def setAlignment(self, alignment):
self.updateCoordinates()
QtGui.QLabel.setAlignment(self, alignment)
def resizeEvent(self, event):
self.updateCoordinates()
QtGui.QLabel.resizeEvent(self, event)
def paintEvent(self, event):
painter = QPainter(self)
if self._direction == Qt.RightToLeft:
self.px -= self.speed()
if self.px <= -self.textLength:
self.px = self.width()
else:
self.px += self.speed()
if self.px >= self.width():
self.px = -self.textLength
painter.drawText(self.px, self.py + self.fontPointSize, self.text())
painter.translate(self.px, 0)
def speed(self):
return self._speed
def setSpeed(self, speed):
self._speed = speed
def setDirection(self, direction):
self._direction = direction
if self._direction == Qt.RightToLeft:
self.px = self.width() - self.textLength
else:
self.px = 0
self.update()
def pause(self):
self.timer.stop()
def unpause(self):
self.timer.start()
class MainWindow(QMainWindow):
def __init__(self, parent=None):
self.signalUpdateUI()
def signalUpdateUI(self):
updateUIThread = Thread(target=self.updateUI)
updateUIThread.daemon = True
updateUIThread.start()
def updateUI(self):
while(1==1):
#update some text color and contents
#update marquee label contents
self.update()
sleep(2)
def paintEvent(self, event):
QWidget.paintEvent(self, event)
painter = QPainter(self)
pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
painter.setPen(pen)
painter.drawLine(0,190, 1920,190)
painter.drawLine(0,300, 1920,300)
painter.drawLine(0,840, 1920,840)
painter.drawLine(0,930, 1920,930)
# Reactangle Box Settings
painter.setPen(self._rectBoxLine_color)
painter.setBrush(self._rectBox_color)
rect = QRect(1430,300,470,535)
painter.drawRect(rect)
painter.setFont(QtGui.QFont('Consolas', 60, QtGui.QFont.Bold))
painter.setPen(QtGui.QColor(0, 0, 0))
painter.drawText(QRect(1430,300,470,535), QtCore.Qt.AlignCenter, self._rect_text)
I don't know why the scrolling message stops after few hours even though the other part UI is functioning.
The implementation of the marqueLabel is efficient so I do not think that is the cause of the error, on the other hand the code that shows is also not executable but what it shows you can notice the misuse of threads for periodic tasks, in the case of the GUI is forbidden to directly modify the GUI from another thread, in addition to the task that is performed is not heavy so you must use a QTimer instead.
from PyQt4 import QtCore, QtGui
class MarqueeLabel(QtGui.QLabel):
def __init__(self, parent=None):
super(MarqueeLabel, self).__init__(parent)
self.px = 0
self.py = 15
self._direction = QtCore.Qt.RightToLeft #Qt.LeftToRight
self.setWordWrap(True)
self.timer = QtCore.QTimer(self, interval=20)
self.timer.timeout.connect(self.update)
self.timer.start()
self._speed = 2
self.textLength = 0
self.fontPointSize = 0
self.setAlignment(QtCore.Qt.AlignVCenter)
self.setFixedHeight(self.fontMetrics().height())
def setFont(self, font, size):
newfont = QtGui.QFont(font, size, QtGui.QFont.Bold)
QtGui.QLabel.setFont(self, newfont)
self.setFixedHeight(self.fontMetrics().height())
def updateCoordinates(self):
align = self.alignment()
if align == QtCore.Qt.AlignTop:
self.py = 10
elif align == QtCore.Qt.AlignBottom:
self.py = self.height() - 10
elif align == QtCore.Qt.AlignVCenter:
self.py = self.height() / 2
self.fontPointSize = self.font().pointSize() / 2
self.textLength = self.fontMetrics().width(self.text())
def setAlignment(self, alignment):
self.updateCoordinates()
QtGui.QLabel.setAlignment(self, alignment)
def resizeEvent(self, event):
self.updateCoordinates()
QtGui.QLabel.resizeEvent(self, event)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
if self._direction == QtCore.Qt.RightToLeft:
self.px -= self.speed()
if self.px <= -self.textLength:
self.px = self.width()
else:
self.px += self.speed()
if self.px >= self.width():
self.px = -self.textLength
painter.drawText(self.px, self.py + self.fontPointSize, self.text())
painter.translate(self.px, 0)
def speed(self):
return self._speed
def setSpeed(self, speed):
self._speed = speed
def setDirection(self, direction):
self._direction = direction
if self._direction == Qt.RightToLeft:
self.px = self.width() - self.textLength
else:
self.px = 0
self.update()
def pause(self):
self.timer.stop()
def unpause(self):
self.timer.start()
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self._rectBoxLine_color = QtGui.QColor(QtCore.Qt.green)
self._rectBox_color = QtGui.QBrush(QtCore.Qt.blue)
self._rect_text = "_rect_text"
self.marquee = MarqueeLabel(self)
self.signalUpdateUI()
def signalUpdateUI(self):
timer = QtCore.QTimer(self, interval=2000)
timer.timeout.connect(self.updateUI)
timer.start()
self.updateUI()
def updateUI(self):
#update some text color and contents
#update marquee label contents
self.marquee.setText(QtCore.QDateTime.currentDateTime().toString())
self.update()
def paintEvent(self, event):
super(MainWindow, self).paintEvent(event)
painter = QtGui.QPainter(self)
pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
painter.setPen(pen)
painter.drawLine(0,190, 1920,190)
painter.drawLine(0,300, 1920,300)
painter.drawLine(0,840, 1920,840)
painter.drawLine(0,930, 1920,930)
# Reactangle Box Settings
painter.setPen(self._rectBoxLine_color)
painter.setBrush(self._rectBox_color)
rect = QtCore.QRect(1430,300,470,535)
painter.drawRect(rect)
painter.setFont(QtGui.QFont('Consolas', 60, QtGui.QFont.Bold))
painter.setPen(QtGui.QColor(0, 0, 0))
painter.drawText(QtCore.QRect(1430,300,470,535), QtCore.Qt.AlignCenter, self._rect_text)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I use PyQt5 and Python2.7
I have UIWidget class, PlayStreaming class and Thread class.
Once a button from UIWidget is pressed and then dictionary object from PlayStreaming is sent to Thread class.
If I remove 'QVariantMap', I can receive Button click signal, but I can't send data.
How can I solve the problem?
My whole code is as follow.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QInputDialog
import cv2
import time
import face_recognition.api as face_recognition
class Thread(QtCore.QThread):
changePixmap = QtCore.pyqtSignal(QtGui.QImage)
updateStatus = QtCore.pyqtSignal(str)
scaled_size = QtCore.QSize(640, 480)
curScale=1.0
facearray=[]
dim=(640,480)
processedImage=[]
def run(self):
cap = cv2.VideoCapture(-1)
cap.set(3,1280);
cap.set(4,1024);
time.sleep(2)
self.maxHeight=cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.maxScale=self.maxHeight/480.0
while True:
ret, frame = cap.read()
if ret:
r=1
rescaleSize=int(480*self.curScale)
if(frame.shape[0] > 480 and frame.shape[1] > 640):
r = rescaleSize / float(frame.shape[0])
self.dim = (int(frame.shape[1] * r), rescaleSize)
processedImage=cv2.resize(frame, self.dim, fx=0.0, fy=0.0)
face_locations = face_recognition.face_locations(processedImage)
if(len(face_locations) > 0):
encodefaces(facelocs)
else:
processedImage=frame.copy()
face_locations = face_recognition.face_locations(processedImage)
if(len(face_locations) > 0):
encodefaces(facelocs)
for face_location in face_locations:
top, right, bottom, left = face_location
cv2.rectangle(frame,(int(right/r),int(top/r)),(int(left/r),int(bottom/r)),(0,255,0),2)
rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
convertToQtFormat = QtGui.QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QtGui.QImage.Format_RGB888)
p = convertToQtFormat.scaled(self.scaled_size, QtCore.Qt.KeepAspectRatio)
self.changePixmap.emit(p)
#QtCore.pyqtSlot(QtCore.QSize)
def scaled(self, scaled_size):
self.scaled_size = scaled_size
#QtCore.pyqtSlot()
def scaleup(self):
self.curScale = self.curScale + 0.1
if self.curScale > self.maxScale:
self.curScale = self.maxScale
self.updateStatus.emit('Cur scale:'+str(self.dim))
#QtCore.pyqtSlot()
def scaledown(self):
self.curScale = self.curScale - 0.1
if self.curScale < 1.0:
self.curScale = 1.0
self.updateStatus.emit('Cur scale:'+str(self.dim))
#QtCore.pyqtSlot('QVariantMap')
def getfacestorecognize(self, clickedInfos):
facearray.append(clickedInfos)
print(clickedInfos['x']+' '+clickedInfos['y']+' '+clickedInfos['name'])
def encodefaces(self, facelocs):
if(len(self.facearray) > 0):
for face in facearray:
r=(self.scaled_size[0]/self.dim[0])
x=int(face['x'])*r
y=int(face['y'])*r
#for loc in facelocs:
class PlayStreaming(QtWidgets.QLabel):
reSize = QtCore.pyqtSignal(QtCore.QSize)
scaleupSignal = QtCore.pyqtSignal()
scaledownSignal = QtCore.pyqtSignal()
transferFaceInfosSignal = QtCore.pyqtSignal()#'QVariantMap'
def __init__(self):
super(PlayStreaming, self).__init__()
self.initUI()
self.mousePressEvent = self.showDialog
#QtCore.pyqtSlot(QtGui.QImage)
def setImage(self, image):
self.label.setPixmap(QtGui.QPixmap.fromImage(image))
def initUI(self):
# create a label
self.label = QtWidgets.QLabel(self)
th = Thread(self)
th.changePixmap.connect(self.setImage)
th.updateStatus.connect(self.handle_status_message)
self.scaleupSignal.connect(th.scaleup)
self.scaledownSignal.connect(th.scaledown)
self.transferFaceInfosSignal.connect(th.getfacestorecognize)
self.reSize.connect(th.scaled)
th.start()
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.label, alignment=QtCore.Qt.AlignCenter)
def resizeEvent(self, event):
self.reSize.emit(self.size())
def showDialog(self, event):
x = event.pos().x()
y = event.pos().y()
facedata={"x": str(x), "y": str(y), "name": ''}
text, ok = QInputDialog.getText(self, 'Name input dialog',
'Enter name:')
if (ok and str(text)!=''):
facedata['name']=str(text)
self.transferFaceInfosSignal.emit(facedata)
def handle_status_message(self, message):
self.window().set_status_message(message)
class UIWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(UIWidget, self).__init__(parent)
# Initialize tab screen
self.tabs = QtWidgets.QTabWidget()
self.tab1 = QtWidgets.QWidget()
self.tab2 = QtWidgets.QWidget()
self.tab3 = QtWidgets.QWidget()
# Add tabs
self.tabs.addTab(self.tab1, "Face")
self.tabs.addTab(self.tab2, "Human")
self.tabs.addTab(self.tab3, "Vehicle")
self.display = PlayStreaming()
# Create first tab
self.createGridLayout()
self.tab1.layout = QtWidgets.QVBoxLayout()
self.tab1.layout.addWidget(self.display, stretch=1)
self.tab1.layout.addWidget(self.horizontalGroupBox)
self.tab1.setLayout(self.tab1.layout)
# Add tabs to widget
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
def createGridLayout(self):
self.horizontalGroupBox = QtWidgets.QGroupBox("")
self.horizontalGroupBox.setStyleSheet("QGroupBox{ background-color: red; border: none;}")
hlay1 = QtWidgets.QHBoxLayout()
self.TestButton=QtWidgets.QPushButton('Test')
hlay1.addWidget(self.TestButton)
self.RunButton=QtWidgets.QPushButton('Run')
hlay1.addWidget(self.RunButton)
self.ScaleUpButton=QtWidgets.QPushButton('ScaleUp')
self.ScaleUpButton.clicked.connect(self.display.scaleupSignal)
hlay1.addWidget(self.ScaleUpButton)
self.ScaleDownButton=QtWidgets.QPushButton('ScaleDown')
self.ScaleDownButton.clicked.connect(self.display.scaledownSignal)
hlay1.addWidget(self.ScaleDownButton)
hlay1.addWidget(QtWidgets.QPushButton('Reset'))
hlay2 = QtWidgets.QHBoxLayout()
hlay2.addWidget(QtWidgets.QPushButton('Set Faces'))
hlay2.addWidget(QtWidgets.QPushButton('FacePose'))
hlay2.addWidget(QtWidgets.QPushButton('Gender'))
hlay2.addWidget(QtWidgets.QPushButton('Age'))
self.RecognizeButton=QtWidgets.QPushButton('Recognize')
self.RecognizeButton.clicked.connect(self.display.transferFaceInfosSignal)
hlay2.addWidget(self.RecognizeButton)
layout = QtWidgets.QVBoxLayout()
layout.addLayout(hlay1)
layout.addLayout(hlay2)
self.horizontalGroupBox.setLayout(layout)
class App(QMainWindow):
def __init__(self):
super(App,self).__init__()
self.title = 'FaceHumanVehicle'
self.left = 10
self.top = 10
self.width = 1000
self.height = 800
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.form_widget = UIWidget(self)
self.statusBar().showMessage('')
self.setCentralWidget(self.form_widget)
self.show()
def set_status_message(self, message):
return self.statusBar().showMessage(message)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
From what I understand you want to send the data when you press the button, so the slot connecting to the button should emit the signal, not connect to the signal. For this the data that I see is filled in mousePressEvent must be a member of the class, in this case the logic is to save the position when the image is pressed, and when the button is pressed a dialogue will be opened, a name will be established and the data will be sent.
class PlayStreaming(QtWidgets.QLabel):
reSize = QtCore.pyqtSignal(QtCore.QSize)
scaleupSignal = QtCore.pyqtSignal()
scaledownSignal = QtCore.pyqtSignal()
transferFaceInfosSignal = QtCore.pyqtSignal('QVariantMap') # <--- +++
def __init__(self):
super(PlayStreaming, self).__init__()
self.facedata = {"x": "", "y": "", "name": ""} # <--- +++
self.initUI()
# self.mousePressEvent = self.showDialog <--- ---
# ...
def mousePressEvent(self, event):
self.facedata["x"] = str(event.pos().x())
self.facedata["y"] = str(event.pos().y())
self.showDialog()
super(PlayStreaming, self).mousePressEvent(event)
def showDialog(self):
text, ok = QtWidgets.QInputDialog.getText(self, 'Name input dialog', 'Enter name:')
if ok and text:
self.facedata['name']= text
#QtCore.pyqtSlot()
def send_signal(self)
if self.facedata["name"]:
self.transferFaceInfosSignal.emit(self.facedata)
class UIWidget(QtWidgets.QWidget):
# ...
def createGridLayout(self):
# ...
self.RecognizeButton.clicked.connect(self.display.send_signal)
# ...
On the other hand the signals and slot support all native python types like dict, so you can replace 'QVariantMap' with dict.
I have written the code for Undo & Redo actions for QTableView by using QUndoStack class in PyQt4.
The Undo action works fine; but when I perform Redo action, I am getting "RuntimeError: maximum recursion depth exceeded while calling a Python object."
I have used QTableView's pressed & dataChanged signals to retrieve the texts from model.
Following is the code sample.
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtSql import *
import os
import sys
import random
# SQL Query:---------------------------------------------------------------------------------------------
def StudentQuery():
StudentQuery = QSqlQuery()
StudentQuery.exec_("DROP TABLE STUDENTS")
StudentQuery.exec_("""CREATE TABLE STUDENTS (
s1 REAL NULL,
s2 REAL NULL,
s3 REAL NULL)""")
Students = ("STD1", "STD2", "STD3")
StudentQuery.prepare("INSERT INTO STUDENTS (s1, s2, s3) VALUES (?, ?, ?)")
for Student in Students:
s1 = random.randint(0, 25)
s2 = random.randint(0, 25)
s3 = random.randint(0, 25)
StudentQuery.addBindValue(QVariant(s1))
StudentQuery.addBindValue(QVariant(s2))
StudentQuery.addBindValue(QVariant(s3))
StudentQuery.exec_()
QApplication.processEvents()
# Ui Dialog:------------------------------------------------------------------------------------------------
class Ui_Student(QDialog):
def __init__(self, parent=None):
super(Ui_Student, self).__init__(parent)
self.setFixedSize(340, 170)
self.setWindowTitle("STUDENT")
self.model = QSqlTableModel(self)
self.model.setTable("STUDENTS")
self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
self.model.select()
self.view = QTableView(self)
self.view.setGeometry(QRect(10, 10, 320, 120))
self.view.setSelectionBehavior(QAbstractItemView.SelectItems)
self.view.setFocusPolicy(Qt.StrongFocus)
self.view.setModel(self.model)
self.view.installEventFilter(self)
QSqlDatabase.database().commit()
# Button Box:---------------------------------------------------------------------------------------------------
self.buttonBox = QDialogButtonBox(self)
self.buttonBox.setGeometry(QRect(118, 127, 100, 45))
self.buttonBox.setOrientation(Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
# SIGNAL & SLOT: -----------------------------------------------------------------------------------------------
QObject.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
QObject.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
# Code For Undo/Redo:---------------------------------------------------------------------------------------------------
self.undoStack = QUndoStack(self)
self.undoStack.setUndoLimit(10)
self.L_Row = []
self.L_Column = []
self.L_Text0 = []
self.L_Text1 = []
self.view.pressed.connect(self.InitialText)
self.view.model().dataChanged.connect(self.FinalText)
def InitialText(self, signal):
self.Row = signal.row()
self.Column = signal.column()
Model = self.view.model()
self.Text0 = Model.data(Model.index(self.Row, self.Column), 0).toString()
self.L_Row.append(self.Row)
self.L_Column.append(self.Column)
self.L_Text0.append(self.Text0)
# print self.L_Text0
def FinalText(self):
View = self.view
Model = self.view.model()
self.Text1 = Model.data(Model.index(self.Row, self.Column), 0).toString()
self.L_Text1.append(self.Text1)
for i in range(len(self.L_Text0)):
if not (self.L_Text0[i] == self.L_Text1[i]):
command = CommandEdit(View, Model, self.L_Row[i], self.L_Column[i],
self.L_Text0[i], self.L_Text1[i], "ABC")
self.undoStack.push(command)
# ContextMenu:---------------------------------------------------------------------------------------------------
def contextMenuEvent(self, event):
menu = QMenu(self)
UndoAction = self.undoStack.createUndoAction(self)
UndoAction.setText("&Undo")
menu.addAction(UndoAction)
UndoAction.setShortcuts(QKeySequence.Undo)
self.connect(UndoAction, SIGNAL("triggered()"), self.undoStack.undo)
RedoAction = self.undoStack.createUndoAction(self)
RedoAction.setText("&Redo")
menu.addAction(RedoAction)
RedoAction.setShortcuts(QKeySequence.Redo)
self.connect(RedoAction, SIGNAL("triggered()"), self.undoStack.redo)
menu.exec_(event.globalPos())
# QUndoCommand Class:---------------------------------------------------------------------------------------------------
class CommandEdit(QUndoCommand):
def __init__(self, View, Model, RowIndex, ColumnIndex, Text0, Text1, description):
super(CommandEdit, self).__init__(description)
self.view = View
self.model = Model
self.rowIndex = RowIndex
self.columnIndex = ColumnIndex
self.text0 = Text0
self.text1 = Text1
def undo(self):
self.model.setData(self.model.index(self.rowIndex, self.columnIndex), QVariant(self.text0))
def redo(self): # Error occurred while executing this function.
self.model.setData(self.model.index(self.rowIndex, self.columnIndex), QVariant(self.text1))
# Code Execute:---------------------------------------------------------------------------------------------------
if __name__ == "__main__":
app = QApplication(sys.argv)
filename = os.path.join(os.path.dirname(__file__), "STD.db")
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(filename)
db.open()
StudentQuery()
form = Ui_Student()
form.show()
sys.exit(app.exec_())
Am I doing something wrong while defining def InitialText & def FinalText?
import tkinter as tk ## most of this is for the Bottoni class
from tkinter import *
import os
import string
import PIL.Image
import PIL.ImageTk
import tkinter.ttk
elenco1 = [elemento1, elemento2, elemento3, elemento4]
elenco2 = [elemento5, elemento6, elemento7, elemento8]
elenco3 = [elemento9, elemento10, elemento11, elemento12]
elenco4 = [elemento13, elemento14, elemento15, elemento16]
BOT = [] ## this is for the Bottoni class
IM = [] ## and this too
elenco = elenco1
class ChangeElenco:
def __init__ (self):
def changeElenco(regione):
if regione == "N":
self.elenco = elenco1
elif regione == "K":
self.elenco = elenco2
elif regione == "J":
self.elenco = elenco3
elif regione == "H":
self.elenco = elenco4
elenco = self.elenco
self.radio1 = Radiobutton(text = '1', value = 1, command = lambda : changeElenco("N")).place (x = 920, y = 150)
self.radio2 = Radiobutton(text = '2', value = 2, command = lambda : changeElenco("K")).place (x = 920, y = 170)
self.radio3 = Radiobutton(text = '3', value = 3, command = lambda : changeElenco("J")).place (x = 920, y = 190)
self.radio4 = Radiobutton(text = '4', value = 4, command = lambda : changeElenco("H")).place (x = 920, y = 210)
class secondWindow:
def __init__(self):
self.secondWindow = Tk()
self.secondWindow.geometry ('500x650+400+30')
class Bottoni:
def __init__ (stringa, elenco):
...
def Destroy (self):
...
class mainWindow:
def __init__(self):
self.mainWindow = Tk()
self.mainWindow.geometry ('1130x650+100+10')
self.mainWindow.title('mainWindow')
def mainEnter (self):
testoEntry = StringVar()
testoEntry.set('')
self.mainEntry = Entry(self.mainWindow, textvariable = testoEntry).place (x = 920, y = 20)
def search ():
testoEntry2 = testoEntry.get()
if testoEntry2 == "":
pass
else:
testoEntry2 = testoEntry2.lower()
Bottoni.Destroy(self)
BOT = []
ChangeElenco() ################ here i need the program to change my list "elenco" when i press a radio button
Bottoni(testoEntry2, elenco)
def tracing(a, b, c):
if len(testoEntry.get()) > 2:
search()
testoEntry.trace('w', tracing)
self.button4Entry = Button (self.mainWindow, text = 'search', command = search).place (x = 1050, y = 17)
MW = mainWindow()
ChangeElenco()
MW.mainEnter()
mainloop()
The problem is that in this code, I need the ChangeElenco class to change me the list, and the list I need is the one I choose with the radio button, but in fact it changes just inside the changeElenco function inside that class, and then the list remains the one I had at the beginning...
I need to make a treeView with 4 columns with a checkbox in the first
column. I have made the tree view, just that I do not put the
checkbox in the first column. I tried but it gets me in every position
(row, column ) ...........
Here is my code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from copy import deepcopy
from cPickle import dumps, load, loads
from cStringIO import StringIO
class myNode(object):
def __init__(self, name, state, description,otro, parent=None,checked=False):
self.name = QString(name)
self.state = QString(state)
self.description = QString(description)
self.otro = QString(otro)
self.parent = parent
self.children = []
self.setParent(parent)
def setParent(self, parent):
if parent != None:
self.parent = parent
self.parent.appendChild(self)
else:
self.parent = None
def appendChild(self, child):
self.children.append(child)
def childAtRow(self, row):
return self.children[row]
def rowOfChild(self, child):
for i, item in enumerate(self.children):
if item == child:
return i
return -1
def removeChild(self, row):
value = self.children[row]
self.children.remove(value)
return True
def __len__(self):
return len(self.children)
class myModel(QAbstractItemModel):
def __init__(self, parent=None):
super(myModel, self).__init__(parent)
self.treeView = parent
self.columns = 4
self.headers = ['Directorio','Peso','Tipo','Modificado']
# Create items
self.root = myNode('root', 'on', 'this is root','asd', None)
itemA = myNode('itemA', 'on', 'this is item A','dfg', self.root)
itemB = myNode('itemB', 'on', 'this is item B','fgh', self.root)
itemC = myNode('itemC', 'on', 'this is item C','cvb', self.root)
def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.headers[section])
return QVariant()
def supportedDropActions(self):
return Qt.CopyAction | Qt.MoveAction
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable| Qt.ItemIsUserCheckable
def insertRow(self, row, parent):
return self.insertRows(row, 1, parent)
def insertRows(self, row, count, parent):
self.beginInsertRows(parent, row, (row + (count - 1)))
self.endInsertRows()
return True
def removeRow(self, row, parentIndex):
return self.removeRows(row, 1, parentIndex)
def removeRows(self, row, count, parentIndex):
self.beginRemoveRows(parentIndex, row, row)
node = self.nodeFromIndex(parentIndex)
node.removeChild(row)
self.endRemoveRows()
return True
def index(self, row, column, parent):
node = self.nodeFromIndex(parent)
return self.createIndex(row, column, node.childAtRow(row))
def data(self, index, role):
if role != Qt.DisplayRole:
return QVariant()
if not index.isValid():
return None
node = self.nodeFromIndex(index)
if role == Qt.DisplayRole:
if index.column() == 0:
return QVariant(node.name)
if role == Qt.CheckStateRole:
if node.checked():
return Qt.Checked
else:
return Qt.Unchecked
if index.column() == 1:
return QVariant(node.state)
elif index.column() == 2:
return QVariant(node.description)
elif index.column() == 3:
return QVariant(node.otro)
else:
return QVariant()
def setData(self, index, value, role=Qt.EditRole):
if index.isValid():
if role == Qt.CheckStateRole:
node = index.internalPointer()
node.setChecked(not node.checked())
return True
return False
def columnCount(self, parent):
return self.columns
def rowCount(self, parent):
node = self.nodeFromIndex(parent)
if node is None:
return 0
return len(node)
def parent(self, child):
if not child.isValid():
return QModelIndex()
node = self.nodeFromIndex(child)
if node is None:
return QModelIndex()
parent = node.parent
if parent is None:
return QModelIndex()
grandparent = parent.parent
if grandparent is None:
return QModelIndex()
row = grandparent.rowOfChild(parent)
assert row != - 1
return self.createIndex(row, 0, parent)
def nodeFromIndex(self, index):
return index.internalPointer() if index.isValid() else self.root
class myTreeView(QTreeView):
def __init__(self, parent=None):
super(myTreeView, self).__init__(parent)
self.myModel = myModel()
self.setModel(self.myModel)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(600, 400)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.treeView = myTreeView(self.centralwidget)
self.treeView.setObjectName("treeView")
self.horizontalLayout.addWidget(self.treeView)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setGeometry(QRect(0, 0, 600, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QApplication.translate("MainWindow",
"MainWindow", None, QApplication.UnicodeUTF8))
if __name__ == "__main__":
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
There are a few things wrong with your example code.
Firstly, your node class is missing some methods:
class myNode(object):
def __init__(self, name, state, description, otro, parent=None, checked=False):
...
self.setChecked(checked)
def checked(self):
return self._checked
def setChecked(self, checked=True):
self._checked = bool(checked)
Secondly, your model's flags method needs to return the correct values:
def flags(self, index):
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if index.column() == 0:
return flags | Qt.ItemIsUserCheckable
return flags
And finally, your model's data method needs to return the correct values:
def data(self, index, role):
if not index.isValid():
return None
node = self.nodeFromIndex(index)
if role == Qt.DisplayRole:
if index.column() == 0:
return QVariant(node.name)
if index.column() == 1:
return QVariant(node.state)
if index.column() == 2:
return QVariant(node.description)
if index.column() == 3:
return QVariant(node.otro)
elif role == Qt.CheckStateRole:
if index.column() == 0:
if node.checked():
return Qt.Checked
return Qt.Unchecked
return QVariant()
QTreeView determine which cell should have checkbox by the result of QAbstractItemModel::flags function. You should return value with Qt.ItemIsUserCheckable only for first column and without for others:
def flags(self, index):
if index.column() == 0:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
return Qt.ItemIsEnabled | Qt.ItemIsSelectable