Kivy Making a Custom TreeViewNode

2019-07-25 00:22发布

问题:

I'm attempting to create a custom TreeViewNode to use with a TreeView. Just want an image with a label next to it, nothing more.

Yet attempting to create a custom node... even replicating how it's done in the source doesn't yield the same results.

TreeViewlabel is literally just a class declaration with a comment in it

class TreeViewLabel(Label, TreeViewNode):
'''there's just a comment here'''

This is my version of the TreeViewLabel for comparison

class TreeViewImageLabel(Label, TreeViewNode):
"""oh boy this is a comment"""

Well attempting to create a carbon copy of this code and adding it to a tree yields the following. My version is the first label, and the subsequent labels are the default TreeViewLabel

It's all spaced out, un-aligned and huge. Nothing as neat and tidy as the TreeViewLabel that comes with kivy.

What the heck is going on? Not only does it look nothing like the TreeViewLabel, but attempting to configure the widget with size, size_hints, pos, etc. does nothing to budge that label from where it is relative to the tree.

My original plan was to have my node inherit from a boxlayout with an image and label stuck in it, but with the sizing of custom nodes it's impossible to get anything that looks like a TreeViewNode given what I know right now.

The solution was found

So this is how it looks with the fix implemented:

For anyone else looking to make a TreeViewNode with a picture and label as I've done, this is the code that got it working:

#python
class TreeViewImageLabel(BoxLayout, TreeViewNode):
    pass

And the .kv

#kivy language
<TreeViewImageLabel>:
height: max(lbl.texture_size[1] + dp(10), dp(24))

    Image:
        size: (max(lbl.texture_size[1] + dp(10), dp(24)), max(lbl.texture_size[1] + dp(10), dp(24)))
        size_hint: (.05, 1)
        id:img
        source: "smiley.png"
    Label:
        size_hint: (.9, 1)
        id:lbl
        text_size: self.width, None
        text: "test"

回答1:

You've only copied part of the TreeViewLabel class. You recreated the Python class, but there is also a kv rule which is applied as well:

<TreeViewLabel>:
    width: self.texture_size[0]
    height: max(self.texture_size[1] + dp(10), dp(24))
    text_size: self.width, None