2
我在努力使QGraphicsLinearLayout
與QGraphicsScene
一起工作,使得一組QGraphicsItem
s在場景中以線性方式定位。我使用下面的方法嘗試:如何正確使用QGraphicsLinearLayout與QGraphicsScene爲了定位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();
}
這是不行的,因爲所有的項目都仍然被置於彼此的頂部,而不是彼此相鄰(根據線性佈局決定佈局)。我究竟做錯了什麼?