Multi Object View Behaviour - Creating an Editor for a HasTraits subclass - enthought

I am currently trying to make a traitsUI GUI for a class that contains many instances of a single object. My problem is very similar to the one solved in MultiObjectView Example TraitsUI.
However, I don't like the idea of using a context as it requires me to write out the same view many times for each object I have (and I might have a lot). So I tried to edit the code to make it so that each Instance of the House object would default to looking like its normal view when it is viewed from the Houses object. It almost worked, except now I get a button that takes me to the view I want rather than seeing the views nested in one window (like the output of the TraitsUI example above).
Is there a way to adapt the below to get the desired output? I think I have to further edit the create_editor function but I can find very little documentation on this - only many links to different trait editor factories...
Thanks,
Tim
# multi_object_view.py -- Sample code to show multi-object view
# with context
from traits.api import HasTraits, Str, Int, Bool
from traitsui.api import View, Group, Item,InstanceEditor
# Sample class
class House(HasTraits):
address = Str
bedrooms = Int
pool = Bool
price = Int
traits_view =View(
Group(Item('address'), Item('bedrooms'), Item('pool'), Item('price'))
)
def create_editor(self):
""" Returns the default traits UI editor for this type of trait.
"""
return InstanceEditor(view='traits_view')
class Houses(HasTraits):
house1 = House()
house2= House()
house3 = House()
traits_view =View(
Group(Item('house1',editor = house1.create_editor()), Item('house2',editor = house1.create_editor()), Item('house3',editor = house1.create_editor()))
)
hs = Houses()
hs.configure_traits()

Would something like this work?
It simplifies things a little bit and gives you a view that contains the list of views for your houses.
# multi_object_view.py -- Sample code to show multi-object view
# with context
from traits.api import HasTraits, Str, Int, Bool
from traitsui.api import View, Group, Item,InstanceEditor
# Sample class
class House(HasTraits):
address = Str
bedrooms = Int
pool = Bool
price = Int
traits_view =View(
Group(
Item('address'), Item('bedrooms'), Item('pool'), Item('price')
)
)
class Houses(HasTraits):
house1 = House()
house2= House()
house3 = House()
traits_view =View(
Group(
Item('house1', editor=InstanceEditor(), style='custom'),
Item('house2', editor=InstanceEditor(), style='custom'),
Item('house3', editor=InstanceEditor(), style='custom')
)
)
if __name__ == '__main__':
hs = Houses()
hs.configure_traits()

Related

Why is it necessary to use constructors in dart programming language classes?

I'm a beginner learning dart from the book dart apprentice and I reached where they were discussing constructors in dart classes, the book was implying that constructors create instances of the class which I understood but I needed more info about constructors. So I googled and some results repeated what was already in the book about it being used to create instances of a class while others also showed that it's used to instantiate class properties, but my problem is with the other answer which I found that they are used to instantiate properties of a class, but my question is: I instantiate all class properties when I create the class by declaring the property variables, like this:
class UserClass{
userClassProperty = "";
anotherUserClassProperty = ""; }
why is the constructor also needed to instantiate class properties?
Often, values are unique to every class instance.
Consider the following example:
class Point {
final int x;
final int y;
const Point(this.x, this.y);
double get distanceToOrigin => sqrt(x * x + y * y);
}
If the x and y values were defined inside the class, it would be pretty useless. Instead, different Point objects can be instantiated with different values, which means the same code can be used for different situations.
Ok, so constructors instantiate or start a class by collecting all the data the class needs to start to start working. Constructors are so important that the dart compiler provides one even if you don't explicitly create one. For example, you create a class for mammals like this :
class Mammal{
String name = "cat";
int numberOfLegs = 2;
}
Although you don't explicitly add a constructor the dart compiler adds a default constructor like this :
class Mammal{
Mammal(); //This is added by dart during the class instantiation by default.
String name = "cat";
int numberOfLegs = 2;
}
Yeah, that's how crucial constructors are to the dart compiler.
And on the topic of why are they necessary even when you declare all the properties by yourself in the class, as hacker1024 said it would make the class pretty useless, as the point of the existence of classes is to create variants but with different properties. Not adding a constructor to your class and defining all the properties in the class would mean that your class doesn't take property arguments which in turn also means that different variants of your class can't be created. Again this goes directly against the point of the existence of dart classes. For example, you have a class like this :
class Mammals{
Strig name = "Human";
int numberOfLegs = 2;
bool hasFur = false;
}
final cat = Mammal();
final human = Mammal();
print(cat.numberOfLegs); //Prints 2
//2
print(human.numberOfLegs); //Also prints 2
//2
print(cat.hasFur);
// false
Yeah, this class is problematic. Cats with 2 legs? You would agree with me that that's not how things are in reality. And also the class is pretty useless in the sense that it's not modular, no matter which kind of mammal we create be it a cat, a sheep or even a cow the name property is going to be the default one we set, that is "Human". When we create a class to simulate mammals we want to be able to define what kind of properties it has, not use some fixed values. So you want to create a class which has a constructor like this :
class Mammals{
Mammals(String name,int noOfLegs, bool hasFur){
this.name = name;
this.noOfLegs = noOfLegs;
this.hasFur = hasFur;
}
String name = "";
int noOfLegs = 0;
bool hasFur = False;
}
final cat = Mammal("Cat", 4, True); //Now you can pass in the properties ou want.
final human = Mammal("Human", 2, false);
print(cat.name); //This prints the customized name of the object cat instead of some fixed value
//Cat
print(human.name); //This prints the customized name of the object human
Now we have two instances of the class with separate property values.
Although this adds a little more code, the modularity benefit is worth it.

Jupyter DataViewer does not offer view to show non basetype objects

I am using a jupyter notebook in Visual Studio Code.
In normal case when for example running a cell that contains a list or similar
my_test_list : list = [1,2,3]
I get the option Show variable in data viewer in the Window Juyper: Variables
But when I have an objects of one of my own classes:
class MyClass():
def __init__(self,val1,val2):
self.val1 = val1
self.val2 = val2
def __repr__(self):
return f"{self.val1} and {self.val2}"
def __str__(self):
return self.__repr__()
and create a new object in another cell with
myObject = MyClass(1,2)
myObject is shown in the Window Juyper: Variables but no button Show variable in data viewer appears.
My question: Is there any way to define a custom representation of for example MyObject that the data viewer can recognise and display or are there any packages that would allow the data viewer to pick up for example the repr or str method?

LibreOffice Tree with columns

I am writing an extension for LibreOffifce.
A tree with columns on my sidebar is needed. (example - https://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html)
I found information about Tree Control and module "tree", e.g. here
https://wiki.openoffice.org/wiki/Treecontrol
https://www.openoffice.org/api/docs/common/ref/com/sun/star/awt/tree/module-ix.html
But I couldn't find anything about writing a tree with columns.
There is a quote "You can provide your own model which must at least support the interface com.sun.star.awt.XTreeModel." in the article "Tree control", but I also couldn't find any information about providing of my own models...
Please, help me find information and examples, if it is possible to provide tree with columns for LibreOffice extension.
Here is some Python-UNO code (as tagged in your question) that shows how to implement the XTreeDataModel UNO interface. You'll have to write a lot more code in order to render the nodes in multiple columns and do everything else you want. It may be required to create another class that implements XTreeNode.
import uno
import unohelper
from com.sun.star.awt.tree import XTreeDataModel
def myTree():
document = XSCRIPTCONTEXT.getDocument()
ctx = XSCRIPTCONTEXT.getComponentContext()
smgr = ctx.getServiceManager()
dlgprov = smgr.createInstanceWithArgumentsAndContext(
"com.sun.star.awt.DialogProvider", (document,), ctx)
dlg = dlgprov.createDialog(
"vnd.sun.star.script:Standard.Dialog1?location=application")
treeCtrl = dlg.getControl("TreeControl1")
treeModel = treeCtrl.getModel()
mutableTreeDataModel = smgr.createInstanceWithContext(
"com.sun.star.awt.tree.MutableTreeDataModel", ctx)
rootNode = mutableTreeDataModel.createNode("Root", True)
mutableTreeDataModel.setRoot(rootNode)
myTree = MyTreeDataModel(rootNode)
model = mutableTreeDataModel
childNode1 = model.createNode("Parent 1", True)
rootNode.appendChild(childNode1)
subChildNode = model.createNode("Child 1", True)
childNode1.appendChild(subChildNode)
treeModel.setPropertyValue("DataModel", myTree)
dlg.execute()
dlg.dispose()
class MyTreeDataModel(unohelper.Base, XTreeDataModel):
def __init__(self, root):
self.rootNode = root
def getRoot(self):
return self.rootNode
def addTreeDataModelListener(self, listener):
pass
def removeTreeDataModelListener(self, listener):
pass
More information for working with trees is at https://wiki.openoffice.org/wiki/Going_further_with_Dialog_and_Component#The_New_Tree_Control.
If it turns out that there is no convenient way to do this directly with UNO, I once did this with a JTreeTable in Java. LibreOffice extensions can be written in Java, so perhaps that would solve your needs instead.

Storing a variable from a class within a class (tkinter)

I am trying to capture the entry value from the pop up window into a variable that I can access later and manipulate. I need to make a lists of several message box entries to generate questions for the user. However, whenever I try to capture it the variable I assign it to comes up empty.
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
class popupWindowID (object):
def __init__(self,master):
top=self.top=Toplevel(master)
self.label=Label(top,text="ID")
self.label.pack()
self.entrybox=Entry(top)
self.entrybox.pack()
self.b=Button(top,text='Enter',command=self.cleanup)
self.b.pack()
def cleanup(self): # This cleans it up so it can be overwritten if needed
self.value=str(self.entrybox.get())
self.top.destroy()
class mainWindow(object):
def __init__(self,master):
self.master=master
self.ID=Button(topFrame,text="ID", command=self.popupID)
self.ID.pack(side = TOP)
self.info=Button(topFrame,text="Show Test Information",command=self.entryValue)
self.info.pack(side = TOP)
def popupID(self):
self.ID=popupWindowID(self.master)
self.master.wait_window(self.ID.top)
def entryValue(self):
print(self.ID.value)
m=mainWindow(root)
root.mainloop()

Inheritance of TraitsUI objects

I am trying to make a Traits gui base class and I have other classes that I want to inherit some items (i.e. groups) from this class. I do not want to completely inherit the view between these classes, just some of the objects.
When I try
For example:
from enthought.traits.api import Int, Str, Array, Instance, HasTraits, Float, Enum, Bool, Range
from enthought.traits.ui.api import View, Group, HGroup, VGroup, Item, spring
class A(HasTraits):
u = Int(23)
i = Int(66)
group1 = Group(Item('u'))
group2 = Group(Item('i'))
main = View(group1,group2)
class B(A):
group1 = a.group1 # I have tried this with a().group1 as well
o = Str('4345')
p = Str('3423')
group2 = Group(Item('o'))
group3 = Group(Item('p'))
main = View(group1,group2,group3)
#----------
I know that this is a ridiculous example, but it illustrates the point. When try to make an instance of class B, I get the error that class A does not have the attribute 'group1'.
In normal python classes this would not be a problem, but somehow these TraitsUI Group objects are hidden. Does anyone know if there is a workaround?
This does work with other Traits type (i.e. Int() ), just not with Groups as far as I've tested.
Thanks!
This may help: Traits UI User Guide / Advanced View Concepts / Include Objects