要在对象悬停在场景中时突出显示文本,您必须重新实现 QGraphicsScene 和 QGraphicsItem(您将使用哪个)以通知主窗口查找和突出显示文本。这是当对象悬停在我使用 QGraphicsPixmapItem 的场景中时突出显示文本的示例代码:
图形场景
class GraphicScene : public QGraphicsScene
{
Q_OBJECT
public:
GraphicScene();
void EmitItemHoverd(QString name)
{
emit SignalItemHovered(name);
}
signals:
void SignalItemHovered(QString);
};
图形项:
#include "GraphicScene.h"
class GraphicItem : public QGraphicsPixmapItem
{
QString itemName;
GraphicScene * scene;
public:
GraphicItem(GraphicScene *s, QString name);//name you can set from editor
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
};
GraphicItem::GraphicItem(GraphicScene *s, QString name)
{
scene = s;
itemName = name;
this->setAcceptHoverEvents(true);
}
void GraphicItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
scene->EmitItemHoverd(itemName);
}
在 MainWindow 构造函数中连接
connect(scene,SIGNAL(SignalItemHovered(QString)),this,SLOT(OnItemHovered(QString)));
这是插槽:
void MainWindow::OnItemHovered(QString name)
{
ui->textEdit->find(name);
QTextCursor tc = ui->textEdit->textCursor();
tc.select(QTextCursor::WordUnderCursor);
ui->textEdit->find("}");
QTextCursor tc1 = ui->textEdit->textCursor();
tc1.select(QTextCursor::WordUnderCursor);
int pos2 = tc1.selectionStart();
tc.setPosition(pos2,QTextCursor::KeepAnchor);
ui->textEdit->setTextCursor(tc);
}
和绘制逻辑:
GraphicItem * item = new GraphicItem(scene,"Circle");
QPixmap map(50,50);
QPainter * painter= new QPainter(&map);
painter->setBrush(QBrush(Qt::red,Qt::SolidPattern));
painter->drawEllipse(20,20,15,15);
item->setPixmap(map);
scene->addItem(item);
ui->graphicsView->update();
delete painter;
注意:在这里使用 public EmitItemHoverd 可能是一个问题,我只是为了解释可以通过所需更改对其进行保护的逻辑。
是的,我知道它的一半答案,但可以根据上面的相反逻辑来实现