在Treeview中获取项目或单元格高度的像素位置

时间:2014-03-26 22:08:10

标签: gtk# gtk2

在GTK#应用程序中,我在ScrolledWindow中使用TreeView,并尝试在TreeStore中找到项目的位置,以便从Cairo中的该项目开始绘制线条。现在,我使用的是单元格高度的硬编码值,适用于少数项目,但是当使用其他字体大小或项目列表变长时,会有一个可见的偏移量。有没有一种方法可以获取TreeView的单元格高度,或者另一种方法来获取TreeStore中项目的垂直位置?

以下是我目前使用的方法:

int GetYPositionForPort (TreeView tree, TreeStore store, Port selectedPort)
{
    // Is there a way to get the cell height?
    int cellHeight = 24;
    // We start in the middle of the first Treeview item
    int position = cellHeight / 2;

    ScrolledWindow treeParent = tree.Parent as ScrolledWindow;
    if (treeParent != null) {
        position -= Convert.ToInt32 (treeParent.Vadjustment.Value);
    }
    TreeIter clientIter;
    TreeIter portIter;
    if (store.GetIterFirst (out clientIter)) {
        do {
            if (store.IterHasChild (clientIter) 
                && tree.GetRowExpanded (store.GetPath (clientIter))) {
                if (store.IterChildren (out portIter, clientIter)) {
                    do {
                        position += cellHeight;
                    } while (((Port)store.GetValue(portIter, 0) != selectedPort 
                        || (Client)store.GetValue(clientIter, 0) != selectedPort.Client) 
                        && store.IterNext(ref portIter));
                }
            }
            //Necessary because the first Treeview item only counts as 1/2 cell height.
            if (((Client)store.GetValue (clientIter, 0)) == selectedPort.Client) {
                break;
            }
            position += cellHeight;
        } while (store.IterNext(ref clientIter));
    }
    return position;
}

您可以在屏幕截图底部看到错误,其中的行与TreeView中的项目不对齐:

Screenshot of the application

1 个答案:

答案 0 :(得分:1)

阅读文档,我想出了以下丑陋的代码:

int GetCellHeight (TreeView tree)
{
    if (_cellHeight > 0) {
        return _cellHeight;
    }
    int offsetX;
    int offsetY;
    int cellWidth;
    Gdk.Rectangle rectangle = new Gdk.Rectangle ();
    TreeViewColumn column = tree.GetColumn (0);

    // Getting dimensions from TreeViewColumn
    column.CellGetSize(rectangle, out offsetX, out offsetY, 
        out cellWidth, out _cellHeight);

    // And now get padding from CellRenderer
    CellRenderer renderer = column.CellRenderers[0];
    _cellHeight += (int)renderer.Ypad;
    return _cellHeight;
}

现在看起来像这样: Current state of program