如何正确使用QGraphicsLinearLayout和QGraphicsScene来定位QGraphicsItems?

时间:2012-04-19 14:49:17

标签: qt layout qgraphicsscene

我正在努力让QGraphicsLinearLayoutQGraphicsScene一起工作,以便一组QGraphicsItem在场景中以线性方式定位。我尝试过使用以下方法:

#include <QApplication>
#include <QBrush>
#include <QGraphicsItem>
#include <QGraphicsLayoutItem>
#include <QGraphicsLinearLayout>
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsWidget>
#include <QPen>

class MyShape : public QGraphicsRectItem, public QGraphicsLayoutItem {
  public:
    MyShape(void) {
        setPen(QPen(QBrush(Qt::black), 1));
        setBrush(QBrush(Qt::green));
        setRect(0, 0, 20, 20);
    }

    virtual QSizeF sizeHint(Qt::SizeHint which,
                            const QSizeF& constraint = QSizeF()) const {
        Q_UNUSED(which);
        Q_UNUSED(constraint);
        return boundingRect().size();
    }
};

int main(int argc, char** argv) {
    QApplication app(argc, argv);

    QGraphicsScene scene;
    MyShape* shape1 = new MyShape;
    MyShape* shape2 = new MyShape;
    MyShape* shape3 = new MyShape;
    scene.addItem(shape1);
    scene.addItem(shape2);
    scene.addItem(shape3);

    QGraphicsLinearLayout* layout = new QGraphicsLinearLayout;
    layout->addItem(shape1);
    layout->addItem(shape2);
    layout->addItem(shape3);

    QGraphicsWidget* container = new QGraphicsWidget;
    container->setLayout(layout);
    scene.addItem(container);

    QGraphicsView view;
    view.setScene(&scene);
    view.show();

    return app.exec();
}

这不起作用,因为所有项目仍然放在彼此之上,而不是彼此相邻(根据线性布局规定的布局)。我做错了什么?

1 个答案:

答案 0 :(得分:3)

啊,我忘了覆盖setGeometry功能!

所以MyShape类的实现应如下所示:

class MyShape : public QGraphicsRectItem, public QGraphicsLayoutItem {
  public:
    MyShape(void) {
        setPen(QPen(QBrush(Qt::black), 1));
        setBrush(QBrush(Qt::green));
        setRect(0, 0, 20, 20);
    }

    virtual QSizeF sizeHint(Qt::SizeHint which,
                            const QSizeF& constraint = QSizeF()) const {
        Q_UNUSED(which);
        Q_UNUSED(constraint);
        return boundingRect().size();
    }

    virtual void setGeometry(const QRectF& rect) {
        setPos(rect.topLeft());
    }
};

现在它按预期工作。 =)