我想创建带有文本项的网格布局,并且希望在将文本添加到文本项后更新此布局,但这不起作用。 这是我的源代码片段:
MyItem::MyItem(const QString &text, QGraphicsLayout* layout, QGraphicsItem *parent):
QGraphicsLayoutItem(),
QGraphicsTextItem(parent),
mLayout(layout)
{
setGraphicsItem(this);
setHtml(text);
setFlag(QGraphicsItem::ItemIsSelectable, true);
}
void MyItem::setGeometry(const QRectF &geom)
{
prepareGeometryChange();
QGraphicsLayoutItem::setGeometry(geom);
setPos(geom.topLeft());
}
QSizeF MyItem::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
return boundingRect().size();
}
void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton && textInteractionFlags() == Qt::NoTextInteraction) {
setTextInteractionFlags(Qt::TextEditorInteraction);
}
QGraphicsTextItem::mousePressEvent(event);
}
void MyItem::focusOutEvent(QFocusEvent *event)
{
setTextInteractionFlags(Qt::NoTextInteraction);
auto cursor = textCursor();
cursor.clearSelection();
setTextCursor(cursor);
QGraphicsTextItem::focusOutEvent(event);
}
void MyItem::keyPressEvent(QKeyEvent *event)
{
QGraphicsTextItem::keyPressEvent(event);
qDebug() << boundingRect();
updateGeometry();
mLayout->activate();
}
结果是,当我在文本项中添加文本并且他的宽度越来越大时,下一个单元格不会移动以放置第一个单元格的位置:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto scene = new QGraphicsScene;
auto layout = new QGraphicsGridLayout;
auto t1 = new MyItem("cell1", layout);
layout->addItem(t1, 0, 0);
auto t2 = new MyItem("cell2", layout);
layout->addItem(t2, 0, 1);
auto container = new QGraphicsWidget;
container->setLayout(layout);
scene->addItem(container);
auto view = new QGraphicsView(scene);
setCentralWidget(view);
resize(800, 600);
}
答案 0 :(得分:0)
在mLayout->updateGeometry();
方法中添加void MyItem::keyPressEvent(QKeyEvent *event)
解决了我的问题。