我的 widget.cpp 中具有以下Qt代码片段:
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_Scene = new QGraphicsScene(this);
m_Scene->setSceneRect(0, 0, 1024, 768);
GraphicsTextItem* m_1 = new GraphicsTextItem(nullptr, QString("l_1"));
GraphicsTextItem* m_2 = new GraphicsTextItem(nullptr, QString("l_2"));
QGraphicsLinearLayout* layout = new QGraphicsLinearLayout;
layout->addItem(m_1);
layout->addItem(m_2);
QGraphicsWidget* list = new QGraphicsWidget;
list->setLayout(layout);
m_Scene->addItem(list);
qDebug() << m_2->x() << " " << m_2->y(); // Prints 0,0 Why?
QGraphicsView* view = new QGraphicsView(this);
view->setScene(m_Scene);
}
GraphicsTextItem是QGraphicsWidget的派生类:
class GraphicsTextItem : public QGraphicsWidget
{
private:
QString m_Name;
public:
GraphicsTextItem(QGraphicsItem * parent = nullptr, const QString& name = QString());
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
QFont font("Times", 12);
painter->setFont(font);
painter->drawText(0, 0, m_Name);
}
};
我还将我的短主线设在 main.cpp :
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
我的问题是为什么qDebug行会向我打印0,0,因为小部件的位置肯定为非零。如果我不将小部件放在布局中,而是调用setPos(),则qDebug将打印以前设置的正确值。
答案 0 :(得分:2)
所有QGraphicsItem的初始位置为(0,0),其中包括m_2,并且应用QGraphicsLinearLayout时m_2将更改其位置,该位置将在同步任务完成并且eventloop开始工作之后的瞬间。使用QTimer::singleShot(0, ...)
进行观察:
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_Scene = new QGraphicsScene(this);
QGraphicsView* view = new QGraphicsView(this);
view->setScene(m_Scene);
m_Scene->setSceneRect(0, 0, 1024, 768);
GraphicsTextItem *m_1 = new GraphicsTextItem(nullptr, QString("l_1"));
GraphicsTextItem *m_2 = new GraphicsTextItem(nullptr, QString("l_2"));
QGraphicsLinearLayout* layout = new QGraphicsLinearLayout;
layout->addItem(m_1);
layout->addItem(m_2);
QGraphicsWidget* list = new QGraphicsWidget;
list->setLayout(layout);
m_Scene->addItem(list);
qDebug() << "synchronous" << m_2->pos() << m_2->mapToScene(QPointF{});
QTimer::singleShot(0, m_2, [m_2](){
qDebug() << "asynchronous"<< m_2->pos() << m_2->mapToScene(QPointF{});
});
}
输出:
synchronous QPointF(0,0) QPointF(0,0)
asynchronous QPointF(62,6) QPointF(62,6)