PyQt4: QAbstractItemModel Object to QStandardItemModel Object - pyqt

I have a QtGui.QAbstractItemModel object. I'd like to create a new QtGui.QStandardItemModel object based on the QtGui.QAbstractItemModel. Because QtGui.QStandardItemModel is sub-classed from QtGui.QAbstractItemModel I should be able to copy all data from one object to another. How do you do so?
Usually you would something like this:
data_model = QtGui.QAbstractItemModel()
new_data_model = QtGui.QAbstractItemModel(data_model)
but the Constructor does not support instantiating with that type of argument.
Any Ideas?

QAbstractItemModel is an abstract class that can not and should not be instantiated. Its usefulness is mainly for inheritance since it serves as a basis for any type of model such as QStandardItemModel.
In addition to passing as a parent a model to another does not imply that the data will be copied, and finally QAbstractItemModel is in the submodule QtCore, not in QtGui.

Related

Can a GDScript class not extend anything?/Is there a class that every class must extend?

I'm making a GDScript class that shouldn't need to extend Node2D. It doesn't have an associated scene, and exists so that other classes in my project can interface with it, but will never be displayed directly by the engine. Can I simply not have the extends keyword at the top of the file?
You can extend Object or any of its descendants, not just Node.
I believe you can omit the extends statement and it will default to inheriting Reference, but you should be explicit and write extends Reference.
Read the docs on Object then Reference then Resource and see which one will work best for you.
You can then instance your new script like:
const MyScript = preload(‘path/to/my_script.gd’)
var my_script := MyScript.new()
Or if you have given your script a class_name you can omit the preload into constant step.

How do I pass the session object of a ThreadLocalODMSession to a class defined in another python file?

I hope I can explain this issue correctly.
I want to define the ThreadLocalODMSession object in one python file, and have defined several other files with the classes that represent the mongo collection. But the sample source code for ming always shows the ThreadLocalODMSession object as a local variable, that sets the session variable in the __mongometa__ subclass of the collection definition class.
In the example, the definition of WikiPage is in the same script as the definition of the ThreadLocalODMSession (called session) object, and get passed in the __mongometa__ definition.
class WikiPage(MappedClass):
class __mongometa__:
session = session
name = 'wiki_page'
I want to be able to pass the session object into the __init__ method of the WikiPage, and then have the __mongometa__ subclass set its copy of session on creation.

Saving Object State with Pickle (objects containing objects)

I'm trying to figure out how to serialize an object with Pickle to a save file. My example is an object called World and this object has a list (named objects) of potentially hundreds of instantiated objects of different class types.
The problem is that Pickle won't let me serialize the items within the World.objects list because they aren't instantiated as attributes of World.
When I attempt to serialize with:
with open('gsave.pkl', 'wb') as output:
pickle.dump(world.objects, output, pickle.DEFAULT_PROTOCOL)
I get the following error:
_pickle.PicklingError: Can't pickle <class 'world.LargeHealthPotion'>:
attribute lookup LargeHealthPotion on world failed
So, my question is: what is an alternative way of storing the world.objects list items so that they are attributes of world rather than list items that don't get saved?
UPDATE
I think my issue isn't where the objects are stored; but rather that the class LargeHealthPotion (and many others) are dynamically created within the World class by operations such as this:
def __constructor__(self, n, cl, d, c, h, l):
# initialize super of class type
super(self.__class__, self).__init__(name=n, classtype=cl, description=d, cost=c,
hp=h, level=l)
# create the object class dynamically, utilizing __constructor__ for __init__ method
item = type(item_name,
(eval("{}.{}".format(name,row[1].value)),),
{'__init__':__constructor__})
# add new object to the global _objects object to be used throughout the world
self._objects[item_name] = item(obj_name, obj_classtype, obj_description, obj_cost,
obj_hp, obj_level)
When this finishes, I will have a new object like <world.LargeHealthPotion object at 0x103690ac8>. I do this dynamically because I don't want to explicitly have to create hundreds of different types of classes for each different type of object in my world. Instead, I create the class dynamically while iterating over the item name (with it's stats) that I want to create.
This introduces a problem though, because when pickling, it can't find the static reference to the class in order to deconstruct, or reconstruct the object...so it fails.
What else can I do? (Besides creating literal class references for each, and every, type of object I'm going to instantiate into my world.)
Pickle does not pickle classes, it instead relies on references to classes which doesn't work if the class was dynamically generated. (this answer has appropriate exert and bolding from documentation)
So pickle assumes that if your object is from the class called world.LargeHealthPotion then it check that that name actually resolves to the class that it will be able to use when unpickling, if it doesn't then you won't be able to reinitialize the object since it doesn't know how to reference the class. There are a few ways of getting around this:
Define __reduce__ to reconstruct object
I'm not sure how to demo this method to you, I'd need much more information about your setup to suggest how to implement this but I can describe it:
First you'd make a function or classmethod that could recreate one object based on the arguments (probably take class name, instance variables etc.) Then define __reduce__ on the object base class that would return that function along with the arguments needed to pass to it when unpickling.
Put the dynamic classes in the global scope
This is the quick and dirty solution. Assuming the class names do not conflict with other things defined in the world module you could theoretically insert the classes into the global scope by doing globals()[item_name] = item_type, but I do not recommend this as long term solution since it is very bad practice.
Don't use dynamic classes
This is definitely the way to go in my opinion, instead of using the type constructor, just define your own class named something like ObjectType that:
Is not a subclass of type so the instances would be pickle-able.
When an instance is it called constructs a new game-object that has a reference to the object type.
So assuming you have a class called GameObject that takes cls=<ObjectType object> you could setup the ObjectType class something like this:
class ObjectType:
def __init__(self, name, description):
self.item_name = name
self.base_item_description = description
#other qualities common to all objects of this type
def __call__(self, cost, level, hp):
#other qualities that are specific to each item
return GameObject(cls=self, cost=cost, level=level, hp=hp)
Here I am using the __call__ magic method so it uses the same notation as classes cls(params) to create instances, the cls=self would indicate to the (abstracted) GameObject constructor that the class (type) of GameObject is based on the ObjectType instance self. It doesn't have to be a keyword argument, but I'm not sure how else to make a coherent example code without knowing more about your program.

python: de-serializing objects

We have classes of this form classA version1, classA version2, classA version3 .. etc. This is same class that has been modified. Each "modification" creates a new version of a class. Each object has a version attribute which refers to the version of the class from which it was derived. eg ObjectA.version =1 # means it was derived from ClassA version1
Here is my problem. During object de-serializing, i would like to use the specific version of the class that was used to used to make the object. For example, if i am de-serializing object ObjectA with version=3 then ClassA version 3 should be used. Source code for all the different variations of the classes is stored.
This looks getting the object first the get the class. Any idea on how to approach this?
You have three options:
Custom serialisation/deserialisation - you can put version information and class information first.
Create a "union class" which has all of the members of all of the class versions, then use that to create an instance of the appropriate class.
Refactor to a common base class, and have each "version" inherit from that class.
I would recommend option 3, because then your versions can co-exist cleanly.

Kohana helper attribute

I have a question that keeps bothering me. Currently, I have started using Kohana 3.2 Framework. I've written a helper to handle some functionality - I have a number of methods, which are (as it should be) declared STATIC. But, all of these methods are somehow working with the database, so I need to load a model. Currently, every method has a non-static variable like this:
$comment = new Model_Comments;
$comment->addComment("abc");
OK, it seems to be working, but then I wanted to get rid of this redundancy by using class attribute to hold the instance of the model (with is class as well).
Something like this:
private static $comment; // Declaring attribute
self::$comment = new Model_Comment; // This is done within helper __constuct method
self::$comment->addComment("abc"); // And call it within the method.
But, I got failed with: Call to a member function addComment() on a non-object
Question is: is it possible to do it ? Maybe there are some other approaches ?
Sorry for a long story and, thanks in advice! :P
A static method cannot call a non-static method without operating on an instance of the class. So, what you're proposing won't work. There may be a way do accomplish something similar, but what about trying the following:
You could implement the singleton or factory pattern for your "helper" class. Then, you could create the model (as an attribute) as you instantiate/return the instance. With an actual instance of your "helper" class, you won't have to worry about the static scope issues.
In other words, you can create a helper-like class as a "normal" class in your application that, upon creation, always has the necessary model available.
I'd be happy to help further if this approach makes sense.
David

Resources