TreeView in Python+QT - python-2.7

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

Related

Modify inbuilt WxPython widget

How to modify the combobox in wxPython to dropdown a checklistbox so I can select the choices?
something like above. I know that ComboBox class is available and I need to inherit it add the feature of checkbox to dropdown list. But I am not getting the proper way to start with it.
Take a look at the ComboCtrl class. It allows you to provide the window that implements the combo's drop-down. There are some examples in the wxPython demo.
I haven't had the time to grind through ComboCtrl and it looks daunting.
However, an approximation of what you want can be achieved by torturing a wx.Dialog.
import wx
import wx.lib.scrolledpanel as scrolled
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "CheckBox Dialog",size=(400,250))
self.panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
self.log = wx.TextCtrl(self.panel, wx.ID_ANY, size=(350,150),style = wx.TE_MULTILINE|wx.TE_READONLY|wx.VSCROLL)
self.button = wx.Button(self.panel, label="Choose Colours")
sizer.Add(self.log, 0, wx.EXPAND | wx.ALL, 10)
sizer.Add(self.button, 0, wx.EXPAND | wx.ALL, 10)
self.panel.SetSizer(sizer)
self.Bind(wx.EVT_BUTTON, self.OnButton)
self.panel.options = ['Red','Green','Black','White','Orange','Blue','Yellow']
self.panel.selected = [0,0,0,0,0,0,0]
def OnButton(self,event):
dlg = ShowOptions(parent = self.panel)
dlg.ShowModal()
if dlg.result:
result_text = 'Selected: '
for item in range(len(dlg.result)):
if dlg.result[item]:
result_text += self.panel.options[item]+' '
self.log.AppendText(result_text+'\n\n')
self.panel.selected = dlg.result
else:
self.log.AppendText("No selection made\n\n")
dlg.Destroy()
class ShowOptions(wx.Dialog):
def __init__(self, parent):
self.options = parent.options
self.selected = parent.selected
o_str = ''
for item in self.options:
o_str = o_str+item+','
wx.Dialog.__init__(self, parent, wx.ID_ANY, "CheckBoxes", size= (400,250))
self.top_panel = wx.Panel(self,wx.ID_ANY)
self.avail_options = wx.TextCtrl(self.top_panel, wx.ID_ANY, o_str,style = wx.TE_READONLY)
self.bot_panel = wx.Panel(self,wx.ID_ANY)
self.scr_panel = scrolled.ScrolledPanel(self,wx.ID_ANY)
top_sizer = wx.BoxSizer(wx.VERTICAL)
scr_sizer = wx.BoxSizer(wx.VERTICAL)
bot_sizer = wx.BoxSizer(wx.VERTICAL)
self.items = []
for item in range(len(self.options)):
self.item = wx.CheckBox(self.scr_panel,-1,self.options[item])
self.item.SetValue(self.selected[item])
self.items.append(self.item)
self.item.Bind(wx.EVT_CHECKBOX, self.Select)
self.saveButton =wx.Button(self.bot_panel, label="Save")
self.closeButton =wx.Button(self.bot_panel, label="Cancel")
self.saveButton.Bind(wx.EVT_BUTTON, self.SaveOpt)
self.closeButton.Bind(wx.EVT_BUTTON, self.OnQuit)
self.Bind(wx.EVT_CLOSE, self.OnQuit)
top_sizer.Add(self.avail_options,0,flag=wx.EXPAND)
for item in self.items:
scr_sizer.Add(item,0)
bot_sizer.Add(self.saveButton,0,flag=wx.CENTER)
bot_sizer.Add(self.closeButton,0,flag=wx.CENTER)
self.scr_panel.SetupScrolling()
self.top_panel.SetSizer(top_sizer)
self.scr_panel.SetSizer(scr_sizer)
self.bot_panel.SetSizer(bot_sizer)
mainsizer = wx.BoxSizer(wx.VERTICAL)
mainsizer.Add(self.top_panel,0,flag=wx.EXPAND)
mainsizer.Add(self.scr_panel,1,flag=wx.EXPAND)
mainsizer.Add(self.bot_panel,0,flag=wx.EXPAND)
self.SetSizer(mainsizer)
self.Select(None)
self.Show()
def Select(self, event):
selection = []
for item in self.items:
x = item.GetValue()
selection.append(x)
selected_text = ''
for item in range(len(selection)):
if selection[item]:
selected_text += self.options[item]+' '
self.avail_options.SetValue(selected_text)
def OnQuit(self, event):
self.result = None
self.Destroy()
def SaveOpt(self, event):
self.result = []
for item in self.items:
x = item.GetValue()
self.result.append(x)
self.Destroy()
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
I created a widget using wx.ComboCtrl, as suggested by Robin Dunn.
Feel free to use it, or modify it any way you like.
You can also find a more advanced version of it on my GitHub account.
import wx
import wx.lib.mixins.listctrl
import operator
import functools
import contextlib
#contextlib.contextmanager
def asCM(function, *args, **kwargs):
"""Used to build with wxWidgets as context managers to help organize code."""
yield function(*args, **kwargs)
class CheckListCtrl(wx.ComboCtrl):
"""A wxListCtrl-like widget where each item in the drop-down list has a check box.
Modified code from: https://github.com/wxWidgets/Phoenix/blob/master/demo/ComboCtrl.py
"""
def __init__(self, parent, myId = None, initial = None, position = None, size = None, readOnly = False, **kwargs):
"""
parent (wxWindow) – Parent window (must not be None)
initial (str) – Initial selection string
readOnly (bool) - Determiens if the user can modify values in this widget
Example Input: CheckListCtrl(self)
"""
self.parent = parent
#Configure settings
style = []
if (readOnly):
style.append(wx.CB_READONLY)
#Create object
super().__init__(parent,
id = myId or wx.ID_ANY,
value = initial or "",
pos = position or wx.DefaultPosition,
size = size or wx.DefaultSize,
style = functools.reduce(operator.ior, style or (0,)))
self.popup = self.MyPopup(self, **kwargs)
def Append(self, *args, **kwargs):
self.popup.Append(*args, **kwargs)
class MyPopup(wx.ComboPopup):
"""The popup control used by CheckListCtrl."""
def __init__(self, parent, *, popupId = None, multiple = True, prefHeight = None,
image_check = None, image_uncheck = None, lazyLoad = False):
"""
multiple (bool) - Determines if the user can check multiple boxes or not
lazyLoad (bool) - Determines if when Create() is called
- If True: Waits for the first time the popup is called
- If False: Calls it during the build process
prefHeight (int) - What height you would prefer the popup box use
- If None: Will calculate what hight to use based on it's contents
- If -1: Will use the default height
"""
self.parent = parent
self.prefHeight = prefHeight
self._buildVar_myId = popupId
self._buildVar_multiple = multiple
self._buildVar_lazyLoad = lazyLoad
self._buildVar_image_check = image_check
self._buildVar_image_uncheck = image_uncheck
super().__init__()
parent.SetPopupControl(self)
def Create(self, parent):
self.checkList = self.MyListCtrl(self, parent,
myId = self._buildVar_myId,
multiple = self._buildVar_multiple,
image_check = self._buildVar_image_check,
image_uncheck = self._buildVar_image_uncheck)
return True
def Append(self, *args, **kwargs):
self.checkList.Append(*args, **kwargs)
def GetControl(self):
return self.checkList
def GetAdjustedSize(self, minWidth, prefHeight, maxHeight):
if (self.prefHeight is -1):
return super().GetAdjustedSize(minWidth, prefHeight, maxHeight)
elif (self.prefHeight is not None):
return (minWidth, min(self.prefHeight, maxHeight))
return self.checkList.GetBestSize(minWidth, prefHeight, maxHeight)
def LazyCreate(self):
return self._buildVar_lazyLoad
class MyListCtrl(wx.ListCtrl, wx.lib.mixins.listctrl.CheckListCtrlMixin):
"""Modified code from: https://github.com/wxWidgets/wxPython/blob/master/demo/CheckListCtrlMixin.py"""
def __init__(self, parent, root, *, myId = None, multiple = False, image_check = None, image_uncheck = None):
"""
multiple (bool) - Determines if the user can check multiple boxes or not
"""
self.parent = parent
#Configure settings
style = [wx.LC_LIST, wx.SIMPLE_BORDER]
if (not multiple):
style.append(wx.LC_SINGLE_SEL)
#Create object
wx.ListCtrl.__init__(self, root, id = myId or wx.ID_ANY, style = functools.reduce(operator.ior, style or (0,)))
wx.lib.mixins.listctrl.CheckListCtrlMixin.__init__(self, check_image = image_check, uncheck_image = image_uncheck)
def Append(self, value, default = False):
"""Appends the given item to the list.
value (str) - What the item will say
default (bool) - What state the check box will start out at
Example Input: Append("lorem")
Example Input: Append("lorem", default = True)
"""
n = self.GetItemCount()
self.InsertItem(n, value)
if (default):
self.CheckItem(n)
def GetBestSize(self, minWidth, prefHeight, maxHeight):
return (minWidth, min(prefHeight, maxHeight, sum(self.GetItemRect(i)[3] for i in range(self.GetItemCount())) + self.GetItemRect(0)[3]))
# this is called by the base class when an item is checked/unchecked
def OnCheckItem(self, index, state):
print(index, state)
if (__name__ == "__main__"):
class TestFrame(wx.Frame):
def __init__(self):
super().__init__(None, wx.ID_ANY, "Lorem Ipsum")
with asCM(wx.Panel, self, wx.ID_ANY) as myPanel:
with asCM(wx.BoxSizer, wx.VERTICAL) as mySizer:
with asCM(CheckListCtrl, myPanel, prefHeight = None) as myWidget:
myWidget.Append("lorem")
myWidget.Append("ipsum", default = True)
myWidget.Append("dolor")
mySizer.Add(myWidget, 0, wx.ALL, 5)
myPanel.SetSizer(mySizer)
####################################
app = wx.App(False)
frame = TestFrame()
frame.Show()
app.MainLoop()

wxpython-how to get return value from custom wx dialog

This is follow up question from wxpython-can we add ok button on pybusyinfo dialog?
I have created custom dialog.It will pop up when we call a function from another function and if user clicks "Dont proceed" button on the dialog window i need to get true/False value to intimate whether particular button is pressed or not and pass that value to function call to proceed further.
But with wx custom dialog i could not any return value since the dialog getting destroyed once we press any button.
Is there any way to get return value from custom dialog class with button click event and can access from outside of class even if it is destroyed.
Thanks in advance.
def main():
print "start execution"
ret = getUserInput("Do you want to proceed?")
if ret:
print "proceed"
else:
print "exit"
def getUserInput(msg):
class Busy(wx.Dialog):
def __init__(self, parent, msg):
wx.Dialog.__init__(self, parent, wx.ID_ANY, "Message", size=(420, 200))
self.panel = wx.Panel(self, wx.ID_ANY)
self.label = wx.StaticText(self.panel, label=msg, pos=(20, 20))
self.gauge = wx.Gauge(self.panel, size=(300, 20), pos=(50, 50), style=wx.GA_HORIZONTAL)
self.livelabel = wx.StaticText(self.panel, label="Time to live:", pos=(50, 80))
self.lltime = wx.StaticText(self.panel, label="30", pos=(130, 80))
self.notProceedButton = wx.Button(self.panel, label="Don't proceed", pos=(50, 100))
self.timeoutButton = wx.Button(self.panel, label="Timer Off", pos=(250, 100))
self.notProceedButton.Bind(wx.EVT_BUTTON, self.notProceed)
self.timeoutButton.Bind(wx.EVT_BUTTON, self.OnNoTimeout)
self.Bind(wx.EVT_CLOSE, self.OnQuit)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.lifetimer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnLifeTimer, self.lifetimer)
self.timer.Start(100)
self.lifetimer.Start(1000)
self.timeoutbutton_pressed = False
self.gauge.SetBackgroundColour(wx.Colour(0, 127, 255, 255)) # Slate Blue
self.gauge.SetRange(100)
self.gauge.SetValue(0)
self.life = 30
self.direction = 1
self.result_text = True
def OnTimer(self, evt): # Update gauge
x = int(self.gauge.GetValue())
if x == 0:
self.direction = 1
elif x == 100:
self.direction = -1
x += self.direction
self.gauge.SetValue(x)
def OnLifeTimer(self, evt): # Update time to live
if self.timeoutbutton_pressed == True:
return
self.life -= 1
self.lltime.SetLabelText(str(self.life))
if self.life < 1:
self.OnQuit(None)
def OnNoTimeout(self, evt): # toggle time to live
if self.timeoutbutton_pressed == False:
self.timeoutbutton_pressed = True
self.timeoutButton.SetLabel("Timer On")
else:
self.timeoutbutton_pressed = False
self.timeoutButton.SetLabel("Timer Off")
def OnQuit(self, event):
self.timer.Stop()
self.lifetimer.Stop()
self.Destroy()
def notProceed(self, event): # return input
self.result_text = False
self.timer.Stop()
self.lifetimer.Stop()
self.Destroy()
app = wx.App()
dlg = Busy(parent = None, msg=msg)
dlg.ShowModal()
return dlg.result_text
Sure. The EndModal method will return whatever return code you want. Ie
def OnLifeTimer(self, evt): # Update time to live
if self.timeoutbutton_pressed == True:
return
self.life -= 1
self.lltime.SetLabelText(str(self.life))
if self.life < 1:
self.EndModal(SOME_ID_THAT_YOU_DEFINED_SOMEWHERE_ELSE)
self.OnQuit(None)
The argument passed to EndModal is returned from ShowModal
app = wx.App()
dlg = Busy(parent = None, msg=msg)
return_code = dlg.ShowModal()
As a side note, you don't have to call Destroy from within the dialog. If you want to retrieve some flag or other information from it you can call Destroy after, ie
app = wx.App()
dlg = Busy(parent = None, msg=msg)
return_value = dlg.ShowModal()
some_other_value = dlg.some_other_value
dlg.Destroy()
Courtesy of user2682863's excellent example of EndModal()
import wx
class getUserInput(wx.Dialog):
def __init__(self, parent, msg):
wx.Dialog.__init__(self, parent, wx.ID_ANY, "Message", size=(420, 200))
self.panel = wx.Panel(self, wx.ID_ANY)
self.label = wx.StaticText(self.panel, label=msg, pos=(20, 20))
self.gauge = wx.Gauge(self.panel, size=(300, 20), pos=(50, 50), style=wx.GA_HORIZONTAL)
self.livelabel = wx.StaticText(self.panel, label="Time to live:", pos=(50, 80))
self.lltime = wx.StaticText(self.panel, label="30", pos=(130, 80))
self.notProceedButton = wx.Button(self.panel, label="Don't proceed", pos=(50, 100))
self.timeoutButton = wx.Button(self.panel, label="Timer Off", pos=(250, 100))
self.notProceedButton.Bind(wx.EVT_BUTTON, self.notProceed)
self.timeoutButton.Bind(wx.EVT_BUTTON, self.OnNoTimeout)
self.Bind(wx.EVT_CLOSE, self.OnQuit)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.lifetimer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnLifeTimer, self.lifetimer)
self.timer.Start(100)
self.lifetimer.Start(1000)
self.timeoutbutton_pressed = False
self.gauge.SetBackgroundColour(wx.Colour(0, 127, 255, 255)) # Slate Blue
self.gauge.SetRange(100)
self.gauge.SetValue(0)
self.life = 30
self.direction = 1
self.result_text = True
def OnTimer(self, evt): # Update gauge
x = int(self.gauge.GetValue())
if x == 0:
self.direction = 1
elif x == 100:
self.direction = -1
x += self.direction
self.gauge.SetValue(x)
def OnLifeTimer(self, evt): # Update time to live
if self.timeoutbutton_pressed == True:
return
self.life -= 1
self.lltime.SetLabelText(str(self.life))
if self.life < 1:
self.OnQuit(None)
def OnNoTimeout(self, evt): # toggle time to live
if self.timeoutbutton_pressed == False:
self.timeoutbutton_pressed = True
self.timeoutButton.SetLabel("Timer On")
else:
self.timeoutbutton_pressed = False
self.timeoutButton.SetLabel("Timer Off")
def OnQuit(self, event):
self.timer.Stop()
self.lifetimer.Stop()
self.EndModal(True)
def notProceed(self, event): # return input
self.result_text = False
self.timer.Stop()
self.lifetimer.Stop()
self.EndModal(False)
app = wx.App()
dlg = getUserInput(parent = None, msg="Do you want to porceed?")
ret = dlg.ShowModal()
if ret:
print "proceed"
else:
print "exit"

How to add a widget in QmdiArea in pyqt?

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.

Custom widget not being marked safe

I'm creating a custom widget to display a choice field as a row of buttons.
So far, I've copied the code from the Django source for rendering a radio-choice field as my starting point:
#html_safe
#python_2_unicode_compatible
class ButtonInput(SubWidget):
input_type = 'radio'
def __init__(self, name, value, attrs, choice, index):
self.name = name
self.value = value
self.attrs = attrs
self.choice_value = force_text(choice[0])
self.choice_label = force_text(choice[1])
self.index = index
if 'id' in self.attrs:
self.attrs['id'] += "_%d" % self.index
self.value = force_text(self.value)
def __str__(self):
return self.render()
def render(self, name=None, value=None, attrs=None):
if self.id_for_label:
label_for = format_html(' for="{}"', self.id_for_label)
else:
label_for = ''
attrs = dict(self.attrs, **attrs) if attrs else self.attrs
return format_html(
'<label{}>{} {}</label>', label_for, self.tag(attrs), self.choice_label
)
def is_checked(self):
return self.value == self.choice_value
def tag(self, attrs=None):
attrs = attrs or self.attrs
final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
return format_html('<input{} />', flatatt(final_attrs))
#property
def id_for_label(self):
return self.attrs.get('id', '')
class ButtonFieldRenderer(ChoiceFieldRenderer):
choice_input_class = ButtonInput
class ButtonSelect(RendererMixin, Select):
renderer = ButtonFieldRenderer
_empty_value = ''
My issue is that this code renders the correct HTML, but it's not marked safe - the HTML code renders onto the page. Given that this code is essentially copied straight from the Django source code, this is very surprising.
What is missing? How do I make my widget class html-safe?
Changing the strings in the render method for u'' worked for me
def render(self, name=None, value=None, attrs=None):
if self.id_for_label:
label_for = format_html(u' for="{}"', self.id_for_label)
else:
label_for = ''
attrs = dict(self.attrs, **attrs) if attrs else self.attrs
return format_html(
u'<label{}>{} {}</label>', label_for, self.tag(attrs), self.choice_label
)

in pyqt how to print "Ctrl+key" in QLineEdit when pressed Ctrl + anyKey

here my kode where I generated event for QLineEdit to put pressed key combination in textline it Ok for Shift key and Alt key but not for Ctrl key why ?
#!/usr/bin/python
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
self.la = QLabel("Press tab in this box:")
self.le = MyLineEdit()
layout = QVBoxLayout()
layout.addWidget(self.la)
layout.addWidget(self.le)
self.setLayout(layout)
self.connect(self.le, SIGNAL("press"),
self.update)
def update(self):
oldText = str(self.le.text())
self.le.setText(self.le.myText)
class MyLineEdit(QLineEdit):
def __init__(self, *args):
QLineEdit.__init__(self, *args)
self.myText = ""
def event(self, event):
if event.type() == QEvent.KeyPress:
if event.modifiers() & Qt.ControlModifier :
in textline it is Ok for Shift key and Alt key I can put by variable self.myText value in textline, but not for Ctrl key why ?
print event.text()
self.myText = "Ctrl+"+ event.text()
self.emit(SIGNAL("press"))
return True
return QLineEdit.event(self, event)
if __name__ == "__main__":
main()
The reason why the original example doesn't work is because many of the Ctrl+key combinations produce control characters - e.g. Ctrl+J produces a newline.
The correct way to capture keyboard combinations is using QKeySequence, which will work for all keys, including function keys, arrow keys, page up/down keys, etc. You can also get translated shortcuts by using QKeySequence.PortableText.
Here's a demo based on the original example:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
self.la = QLabel("Press tab in this box:")
self.le = MyLineEdit()
layout = QVBoxLayout()
layout.addWidget(self.la)
layout.addWidget(self.le)
self.setLayout(layout)
self.le.keyPressed.connect(self.update)
def update(self, text):
self.le.setText(text)
MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META)
class MyLineEdit(QLineEdit):
keyPressed = pyqtSignal(str)
def keyPressEvent(self, event):
keyname = ''
key = event.key()
modifiers = int(event.modifiers())
if (modifiers and modifiers & MOD_MASK == modifiers and
key > 0 and key != Qt.Key_Shift and key != Qt.Key_Alt and
key != Qt.Key_Control and key != Qt.Key_Meta):
keyname = QKeySequence(modifiers + key).toString()
print('event.text(): %r' % event.text())
print('event.key(): %d, %#x, %s' % (key, key, keyname))
self.keyPressed.emit(keyname)
if __name__ == "__main__":
main()
it is possible when we use key() method which return int value of keys,then we just convert int to char using unichr() function
class MyLineEdit(QLineEdit):
def __init__(self, *args):
QLineEdit.__init__(self, *args)
def event(self, event):
self.myText = ""
event_key = ""
if event.type() == QEvent.KeyPress:
if event.text() != "" :
event_key = str(unichr(event.key())).lower()
if event.modifiers()== Qt.ControlModifier :
print event.text()
self.myText = "Ctrl+" + event_key
self.emit(SIGNAL("press"))
return True
return QLineEdit.event(self, event)