while working with QTreeView() i got this error in rowCount() method. Apparently syntax seems ok. Help please. Related Code lines are
def rowCount(self, parent):
if not parent.isvalid():
parentNode = self._rootNode
else:
parentNode = parent.internalPointer()
return parentNode.childCount()
Related
Recently while getting my hands on with Python Class concepts, I came upon this observation and was not able to understand.
When I try and create instance out of the below class interactively(Python console), I also get the Finding __len__ line in output.
class MyClass(object):
counter = 0
data = 'Class Variable'
def __init__(self):
self.counter += 1
self.value = -1
def __str__(self):
return "Instance {} is the {} instance".format(self.__class__.__name__, self.counter)
def __getattr__(self, item):
print(f'Finding {item}')
return self.__dict__.get(item, f'Attr {item} not available, {self.__dict__}')
def __setattr__(self, key, value):
if key not in self.__dict__:
self.__dict__[key] = value
def __delattr__(self, item):
print(f'Deleting attr: {item}')
if item in self.__dict__:
del self.__dict__[item]
else:
print(f'Cannot find {item} in {self.__dict__}')
if __name__ == '__main__':
inst = MyClass()
print(inst.id)
But running it as a top level module, doesn't add this additional line in output.
Can someone help me understand, why Finding __len__ output would be displayed interactively.
Below is an interactive output,
import WS1
x = WS1.MyClass()
Finding __len__
x.name = 'Yathin'
Finding __len__
I am modifying tk.Entry() to validate a numeric input and notify a user if there was an error in applying it.
Beginning with the code below:
import tkinter as tk
class FloatEntry(tk.Entry):
def __init__(self, parent, *args, **kwargs):
tk.Entry.__init__(self, parent, validate="focusout", validatecommand=self.validate, *args, **kwargs)
def validate(self):
try:
print(float(self.get()))
return True
except ValueError as e:
print(e)
return False
if __name__ == "__main__":
root = tk.Tk()
root.bind_all("<1>", lambda event:event.widget.focus_set()) # make all widgets focusable
var = tk.DoubleVar()
frame = tk.Frame()
frame.pack(fill="both", expand=True)
FloatEntry(frame, textvariable=var).pack()
tk.Label(frame, textvariable=var).pack()
root.mainloop()
This results in the exception being triggered and printing, "could not convert string to float:". After this, neither the try nor the except in validate() are triggered again, so I assume it somehow returned None and disabled validation (I could be wrong here).
If I change the variable var = DoubleVar() to var =tk.StringVar(), then the validation works as expected, printing the float if the string can be parsed as a float, and printing the exception otherwise.
Finally, if I add a check to the value returned by get() before the try/except block, validation works as expected as well.
def validate(self):
try:
val = self.get()
if(val is not ''):
print(float(self.get()))
return True
except ValueError as e:
print(e)
return False
What is causing validation to be disabled on creation of a FloatEntry object?(or if that isn't happening, what is?)
I'll be honest and say I don't fully understand why this is happening. However, a simple workaround seems to be to configure the validatecommand after you've called the __init__ of the superclass:
class FloatEntry(tk.Entry):
def __init__(self, parent, *args, **kwargs):
tk.Entry.__init__(self, parent, validate="focusout", *args, **kwargs)
self.configure(validatecommand=self.validate)
When I make the above changes, I see the validate being called every time the widget loses focus.
I can't resolve this problem:/ My code returned a bound method, not a len of the set. Help me with your advise, please!)
class PowerSet():
def __init__(self):
self.powerset = set()
def size(self):
return len(self.powerset)
def put(self, value):
if value in self.powerset:
raise KeyError
else:
return self.powerset.add(value)
a = PowerSet()
for i in range(10):
a.put(i)
print(a.size)
# <bound method PowerSet.size of <__main__.PowerSet object at 0x7f7291042940>>
but
print(len(a.powerset))
# 10
I think you just have to write len(a.size()) with brackets. Now you are asking to print the method, you are not callng it.
I keep getting an "unresolved reference" error even though I made a statement to it.
verb_dict = {"say": say, "examine": examine}
The error is after the examine:
def examine(noun):
if noun in GameObject.objects:
return GameObject.objects[noun].get_desc()
else:
return "There is no {}".format(noun)
Did I do something wrong when coding it?
I am also using pycharm community edition.
I can't replicate your problem in PyCharm 2016.14 I run the following code with no issue:
class GameObject:
class_name = ""
objects = {}
def __init__(self, name):
self.name = name
GameObject.objects[self.class_name] = self
def examine(noun):
if noun in GameObject.objects:
return GameObject.objects[noun].get_desc()
else:
return "There is no {}".format(noun)
print(examine('try'))
Output is
>>> There is no try
This is the GameObject class.
I don't see a problem in there.If you need more tell me.
class GameObject:
class_name = ""
desc = ""
objects = {}
def __init__(self, name):
self.name = name
GameObject.objects[self.class_name] = self
I set filter on my QMainWindow with this:
keyPressFilter = keypressfilter.KeyPressFilter(self)
self.installEventFilter(keyPressFilter)
KeyPressFilter itself:
class KeyPressFilter(QObject):
def __init__(self, parent=None):
super(KeyPressFilter, self).__init__(parent)
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
print "key press %d" % event.key()
return True
else:
return QObject.eventFilter(obj, event) <- line NN
and i getting endless errors with every eventtype QEvent\QPaintEvent\QHoverEvent\etc:
line NN, in eventFilter:
TypeError: QObject.eventFilter(QObject, QEvent): argument 2 has unexpected type 'QPaintEvent'
How can i get rid of it?
Thx in advance,
Serge
eventFilter() is not a class method, so you need to pass self as well:
return QObject.eventFilter(self, obj, event)