用两个QGraphicsSimpleTextItem-s做一个QGraphicsItemGroup?

1 人关注

假设我想在某个 场景图 一个简单的家谱树。那里的每个人都正好有一个名字和一个姓氏(没有其他显示)。

对于那里的每个人,我想建立一个 QGraphicsItemGroup 由两个 QGraphicsSimpleTextItem -s vertically aligned and centered. One for first names of persons, one for their family names. Each having its own font & color. I don't want to use a heavy 绘图文本项目(QGraphicsTextItem 因为它太沉重了(一个只有姓和名的人名不值得一个完整的 QTextDocument ).

所以我在想

 struct Person {
   QGraphicsItemGroup _group;
   QGraphicsLinearLayout _lay;
   QGraphicsSimpleTextItem _firstname;
   QGraphicsSimpleTextItem _lastname;
 public:
   Person(QGraphicsScene*scene, 
          const std::string& first, const std::string& last) 
   : group(), _lay(Qt::Vertical), 
     _firstname(first.c_str()), _lastname(last.c_str()) {
      _lay.addItem(&_firstname);
      _lay.setSpacing(0, 5);
      _lay.addItem(&_lastname);
      _group.addToGroup(&_firstname);
      _group.addToGroup(&_lastname);
      scene->addItem(&_group);

但这不起作用,因为_lay.addItem(&_firstname);不能编译,因为一个QGraphicsSimpleTextItem不是一个QGraphicsLayoutItem

有什么提示吗?或者我的整个方法是错误的?

我是否应该定义一个既继承于QGraphicsSimpleTextItem又继承于QGraphicsLayoutItem的类?

注:实际代码(GPlv3许可)在我的玄武门 project on github, file guiqt.cc, commit 99fd6d7c1ff261.这不是一个家谱项目,而是一个抽象的语法树编辑器,类似于一个具有持久性的解释器的东西。所关注的类是BxoCommentedObjrefShow;我显示的不是名字,而是像_7rH2hUnmW63o78UGC这样的id,而不是姓氏,我显示的是像body of test1_ptrb_get这样的简短评论。在这里,我想说的是玄武门该项目本身是一个暂定的重写项目。melt-monitor-2015 in C++11 & Qt5

1 个评论
没有人对这个问题有任何线索吗?
linux
c++11
qt5
Basile Starynkevitch
Basile Starynkevitch
发布于 2016-11-12
1 个回答
Adrian Maire
Adrian Maire
发布于 2016-11-22
已采纳
0 人赞同

你似乎给QGraphicsLinearLayout设定了一个目的,而这并不是它的真正目的。

From 官方QT 5.7文档

QGraphicsLinearLayout类提供了一个水平或垂直的布局来管理 widgets 在图形视图中

它不应该在你的场景中布置普通的绘图项目,而是QWidgets。不幸的是,关于它的文档和例子似乎并不奏效。

如何实现垂直布局

幸运的是,QGraphicsItem的扩展并不困难,所以你可以在几行中实现你的一对文本。

#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsSimpleTextItem>
#include <QGraphicsItemGroup>
class QGraphicsPerson: public QGraphicsItemGroup
public:
    QGraphicsPerson( const QString& firstStr,
                     const QString& secondStr,
                     QGraphicsItem *parent=nullptr)
        first.setText(firstStr);
        second.setText(secondStr);
        addToGroup(&first);
        addToGroup(&second);
        second.setPos(first.pos().x(), first.pos().y()+first.boundingRect().height());
protected:
    QGraphicsSimpleTextItem first, second;
int main(int n, char **args)
    QApplication app(n, args);
    QGraphicsScene scene;
    QGraphicsView window(&scene);
    QGraphicsPerson person( "Adrian", "Maire");
    scene.addItem(&person);
    person.setPos(30,30);
    QGraphicsPerson person2( "Another", "Name");
    scene.addItem(&person2);
    window.show();