【问题标题】:What exactly are the positioning rules for text in Qt?Qt中文本的定位规则到底是什么?
【发布时间】:2021-01-30 08:25:51
【问题描述】:

这是一段非常基本的代码:

  1. 测量一段文本的大小。
  2. 在坐标 (100, 25) 处绘制与此大小对应的矩形。
  3. 在坐标 (100, 25) 处显示文本。
auto str = "Hello, World!";
auto metrix = window->fontMetrics();
auto text = scene->addText(str);
text->setPos(100, 25);
text->setDefaultTextColor(Qt::white);

auto r = metrix.boundingRect(str);
int x, y, w, h;
r.getRect(&x, &y, &w, &h);
scene->addRect(100, 25, w, h, QPen(Qt::white));

代码中的scene 是一个QGraphicsScene,没有特定的自定义,除了边框设置为零。

我希望文本正好在矩形内。然而,文本向左移动了几个像素,向下移动了几个像素。为什么?

【问题讨论】:

  • @drescherjm:我应该指定文本是在QGraphicsScene 上绘制的。如果我理解正确,文本没有实际限制,即它可能不会完全显示在场景中,但不应该有自动换行或类似的东西。

标签: c++ qt qt5


【解决方案1】:

解决方案

按照@NgocMinhNguyen 的建议,将文档边距设置为0 似乎可行,但这不是真正的解决方案,因为您会丢失边距。如果你能得到实际的几何图形,包括边距等,那就更好了。为此,你可以使用QGraphicsTextItem::boundingRect() 而不是QFontMetrics::boundingRect

示例

这是我为您编写的一个最小且完整的示例,以演示建议的解决方案:

#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QBoxLayout>

struct MainWindow : public QWidget
{
    MainWindow(QWidget *parent = nullptr) : QWidget(parent) {
        QPointF p(100, 25);
        auto *l = new QVBoxLayout(this);
        auto *view = new QGraphicsView(this);
        auto *textItem = new QGraphicsTextItem(tr("HHHHHHHH"));
        auto *rectItem = new QGraphicsRectItem(textItem->boundingRect()
                                               .adjusted(0, 0, -1, -1));

        textItem->setPos(p);
        rectItem->setPos(p);

        view->setScene(new QGraphicsScene(this));
        view->scene()->addItem(textItem);
        view->scene()->addItem(rectItem);

        l->addWidget(view);

        resize(300, 300);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

注意:请注意我是如何创建矩形的。有区别

auto *item = new QGraphicsRectItem(100, 25, w, h);

auto *item = new QGraphicsRectItem(0, 0, w, h);
item->setPos(100, 25);

结果

此示例产生以下结果:

【讨论】:

    【解决方案2】:

    QGraphicsTextItemQTextDocument 持有,它可以有一个margin
    将边距设置为0,矩形将被正确绘制。

    text->document()->setDocumentMargin(0);
    

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2016-06-23
      相关资源
      最近更新 更多