不能显示QGraphicsItem提示

时间:2022-03-21 23:19:10

I subclass a QGraphicsItem to Node, but when I set it's tooltip, it can't show tooltip when mouse touch it.

我将一个QGraphicsItem子类化到Node,但是当我设置它的工具提示时,当鼠标触到它时,它不能显示工具提示。

There is some of my code:

我的一些代码:

class Node : public QGraphicsItem {
 public:
    Node(int id);
    ~Node() {}
  int id;
private:
  QRectF boundingRect() const;
  void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
};




void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                 QWidget *widget) {
  QPen pen(Qt::red);
  painter->setPen(pen);
  painter->setBrush(Qt::red);
  painter->drawRoundRect(-10, -10, 10, 10);
}

QRectF Node::boundingRect() const {
  QRectF rect;
  rect.translate(-rect.center());
  return rect;
}



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);

  view = new QGraphicsView(this);
  scene = new QGraphicsScene(0, 0, 2000, 2000);
  view->setScene(scene);

  setCentralWidget(view);
  generateMap();
  ui->actionQuery_path->setToolTip(
      "query the shortest path between to loactions");
  view->show();
}


void MainWindow::generateMap() {
  // waterhome
  Node *waterhome = new Node(1);
  waterhome->setToolTip("开水房");
  waterhome->moveBy(100, 470);
  scene->addItem(waterhome);
}

Now I can see my node, but can't see it's tooltip even the action's tooltip, I try to increase the Node's Z value, but it doesn't help, what's wrong?

现在我可以看到我的节点,但是看不到它的工具提示,甚至是动作的工具提示,我尝试增加节点的Z值,但是它没有帮助,怎么了?

1 个解决方案

#1


1  

The problem is with your boudingRect() function. Have a look at it and try to guess what is returns back.

问题在于您的boudingRect()函数。看看它,试着猜猜什么是返回。

If you copy-paste following code then the tooltip should appear:

如果你复制粘贴下面的代码,那么工具提示应该出现:

QRectF Node::boundingRect() const
{
    qreal penWidth = 1;
    return QRectF(-10 - penWidth / 2, -10 - penWidth / 2,
                  20 + penWidth, 20 + penWidth);

}

void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QPen pen(Qt::red);
    painter->setPen(pen);
    painter->setBrush(Qt::red);
    painter->drawRoundedRect(-10, -10, 20, 20, 2, 2);

}

#1


1  

The problem is with your boudingRect() function. Have a look at it and try to guess what is returns back.

问题在于您的boudingRect()函数。看看它,试着猜猜什么是返回。

If you copy-paste following code then the tooltip should appear:

如果你复制粘贴下面的代码,那么工具提示应该出现:

QRectF Node::boundingRect() const
{
    qreal penWidth = 1;
    return QRectF(-10 - penWidth / 2, -10 - penWidth / 2,
                  20 + penWidth, 20 + penWidth);

}

void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QPen pen(Qt::red);
    painter->setPen(pen);
    painter->setBrush(Qt::red);
    painter->drawRoundedRect(-10, -10, 20, 20, 2, 2);

}