Making widgets partly overlap in a Qt layout

醉酒当歌 提交于 2019-12-04 12:21:02

You will need to implement a subclass of QLayout. There is a detailed example in the QT documentation addressing exactly you problem: Layout Management

Basically, you will need to define the following:

  • A data structure to store the items handled by the layout. Each item is a QLayoutItem.

  • addItem(), how to add items to the layout.

  • setGeometry(), how to perform the layout.

  • sizeHint(), the preferred size of the layout.

  • itemAt(), how to iterate over the layout.

  • takeAt(), how to remove items from the layout.

In most cases, you will also implement minimumSize().

Below I have copied the most important part of the code in the example, for your convenience:

class CardLayout : public QLayout
{
public:
    CardLayout(QWidget *parent, int dist): QLayout(parent, 0, dist) {}
    CardLayout(QLayout *parent, int dist): QLayout(parent, dist) {}
    CardLayout(int dist): QLayout(dist) {}
    ~CardLayout();

    void addItem(QLayoutItem *item);
    QSize sizeHint() const;
    QSize minimumSize() const;
    int count() const;
    QLayoutItem *itemAt(int) const;
    QLayoutItem *takeAt(int);
    void setGeometry(const QRect &rect);

private:
    QList<QLayoutItem*> list;
};


void CardLayout::setGeometry(const QRect &r)
{
    QLayout::setGeometry(r);

    if (list.size() == 0)
        return;

    int w = r.width() - (list.count() - 1) * spacing();
    int h = r.height() - (list.count() - 1) * spacing();
    int i = 0;
    while (i < list.size()) {
        QLayoutItem *o = list.at(i);
        QRect geom(r.x() + i * spacing(), r.y() + i * spacing(), w, h);
        o->setGeometry(geom);
        ++i;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!