gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:35:50 31 4
gpt4 key购买 nike

我正在努力让 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();
}

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

最佳答案

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

现在它按预期工作。 =)

关于qt - 如何正确使用 QGraphicsLinearLayout 和 QGraphicsScene 来定位 QGraphicsItems?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10230696/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com