I subclass a QGraphicsItem to Node, but when I set it's tooltip, it can't show tooltip when mouse touch it.
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?
The problem is with your boudingRect() function. Have a look at it and try to guess what is returns back.
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);
}