3

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

#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();
}

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

4

1 回答 1

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());
    }
};

现在它按预期工作。=)

于 2012-04-19T15:06:30.340 回答