【问题标题】:How to correctly use QGraphicsLinearLayout together with QGraphicsScene in order to position QGraphicsItems?如何正确使用 QGraphicsLinearLayout 和 QGraphicsScene 来定位 QGraphicsItems?
【发布时间】:2012-04-19 14:49:16
【问题描述】:

我正在努力让QGraphicsLinearLayoutQGraphicsScene 一起工作,这样一组QGraphicsItems 在现场以线性方式定位。我尝试使用以下方法:

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

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

【问题讨论】:

    标签: qt layout qgraphicsscene


    【解决方案1】:

    啊,我忘了覆盖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());
        }
    };
    

    现在它按预期工作。 =)

    【讨论】:

    • 谢谢,这有帮助。顺便说一句,你可以接受这个答案;)
    猜你喜欢
    • 2020-11-06
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2015-11-02
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多