创建继承QLayout的自定义布局

时间:2018-06-14 10:07:08

标签: c++ qt layout qlayout

我正在编写一个对角线布局来理解布局的机制。这是一个培训计划,我知道我可以为此目的创建一个QGridLayout,但目标是创建继承QLayout的特定布局

我在QSizePolicy::ExpandFlag处理过,但我无法理解如何与QSizePolicy::GrowFlag和其他人合作。

void DiagonalLayout::setGeometry(const QRect &rect)
{
    QLayout::setGeometry(rect);

    int left, top, right, bottom;
    getContentsMargins(&left, &top, &right, &bottom);
    QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
    int x = effectiveRect.x();
    int y = effectiveRect.y();

    int totalNonExpandingWidth = 0;
    int totalNonExpandingHeight = 0;

    int expandingHeightCounter = 0;
    int expandingWidthCounter = 0;

    int expandingWidth = 0;
    int expandingHeight = 0;

    QLayoutItem *item;
    //calculate all expandings
    foreach (item, list)
    {
        const QSize sizeHint = item->sizeHint();
        const Qt::Orientations expanding = item->expandingDirections();

        if (expanding.testFlag(Qt::Horizontal))
            expandingWidthCounter++;
        else
            totalNonExpandingWidth += sizeHint.width();

        if (expanding.testFlag(Qt::Vertical))
            expandingHeightCounter++;
        else
            totalNonExpandingHeight += sizeHint.height();
    }

    if (expandingHeightCounter)
        expandingHeight = (effectiveRect.height() - totalNonExpandingHeight) / expandingHeightCounter;

    if (expandingWidthCounter)
        expandingWidth = (effectiveRect.width() - totalNonExpandingWidth) / expandingWidthCounter;

    //setGeometry for each item taking into account expanding ones
    foreach (item, list)
    {
        const Qt::Orientations expanding = item->expandingDirections();
        int nextX = 0;
        int nextY = 0;
        QSize currentSize(0,0);

        if (expanding.testFlag(Qt::Horizontal))
        {
            currentSize.setWidth(expandingWidth);
            nextX = x + expandingWidth;
        }
        else
        {
            currentSize.setWidth(item->sizeHint().width());
            nextX = x + item->sizeHint().width();
        }

        if (expanding.testFlag(Qt::Vertical))
        {
            currentSize.setHeight(expandingHeight);
            nextY = y + expandingHeight;
        }
        else
        {
            currentSize.setHeight(item->sizeHint().height());
            nextY = y + item->sizeHint().height();
        }

        item->setGeometry(QRect(QPoint(x, y), currentSize));

        x = nextX;
        y = nextY;
    }
}

DiagonalLayout with all Widgets with QSizePolicy::Preferred

DiagonalLayout with all Widgets with QSizePolicy::Preferred except 1st which is QSizePolicy::Expanding

是的,我已阅读QLayout管理页面和所有示例,甚至尝试阅读QBoxLayout源以了解他们是如何做到的。但是来源似乎很难理解,而且Qt示例没有提供足够的信息。

将感谢任何帮助,任何其他来源以及您自己继承QLayout的示例。

0 个答案:

没有答案