如何在QScrollArea中居中的小部件?

时间:2017-09-29 21:42:05

标签: c++ qt graphics

构造

ScrollArea::ScrollArea(...)
{
    ...
    end = myItems.count();
    for(int i=0; i<end; i++)
    {
        scrollItems.append(new ScrollItem(myItems.at(i), 0, width, i, this));
    }
    scrollArea->setWidget(this);    //must be last for auto-scrolling to work
}

会员功能:

void ScrollArea::updateSelection(int selection)
{
    foreach(ScrollItem* item, scrollItems)
    {
        if(item->updateSelection(selection, 0))
        {
            scrollArea->ensureWidgetVisible(item);
        }
    }
}

运行ScrollArea::updateSelection后,它看起来像这样:

enter image description here

我希望它看起来像这样:

enter image description here

谷歌回复了一个错误标题的问题(据我所知:Place widget in center of QScrollArea)和一堆垃圾。

1 个答案:

答案 0 :(得分:0)

仍然不知道QScrollArea::ensureWidgetVisible为什么不起作用,即使有明确的边距,但我发现了一些有用的东西:

void ScrollArea::updateSelection(int selection)
{
    int item = -1;

    int i = scrollItems.count();
    while(i)
    {
        i--;
        if(scrollItems.at(i)->updateSelection(selection, 0))
        {
            item = i;
        }
    }

    if(item < 0)
    {
        return;
    }

    i = scrollItems.first()->height();
    item *= i;
    item += i / 2;
    //item is now the position that should be centered

    scrollArea->verticalScrollBar()->setValue(
                item - (scrollArea->height() / 2)
                );
}

所以我基本上是强迫我想要的,而不是让图书馆这样做。 (并且失败)

相关问题