本次使用了QGraphicsView來加載圖像,然后給其設(shè)置了一個QGraphicsScene場景,再給場景添加了一個自定義的QGraphicsItem,在其中重寫了paint事件,用來重繪圖像。
正常情況時,QGraphicsItem上圖像的有效區(qū)域QRect大小和QGraphicsView一致,此時正好鋪滿,鼠標位置的坐標可以比較輕松的推算出其在圖像有效區(qū)域的全局坐標。
當個人碰到的某些時候,QGraphicsItem上圖像的有效區(qū)域QRect大小并不和QGraphicsView一致,比如寬度留白了,即左右兩邊有空缺。此時發(fā)現(xiàn)如果用正常的方法去獲取鼠標位置坐標在圖像有效區(qū)域的全局坐標,會得到不準確的坐標。明明是鼠標在圖像的頂點,卻可能x坐標或y坐標不從0開始。
文章來源:http://www.zghlxwxcb.cn/news/detail-815033.html
針對這種情況,使用以下幾句可以得到鼠標位置在圖像有效區(qū)域的全局坐標。
class ImgShow : public QObject, public QGraphicsItem
{
Q_OBJECT
public:
ImgShow(QRectF rect);
~ImgShow() override;
void UpdateImageRect(QRectF rect);
void UpdateImageShow(QPixmap pix);
protected:
virtual QRectF boundingRect() const override;
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
void hoverMoveEvent(QGraphicsSceneHoverEvent* event);
private:
QRectF curRect;
QPixmap curPix;
QMutex mtx;
};
cpp文章來源地址http://www.zghlxwxcb.cn/news/detail-815033.html
ImgShow::ImgShow(QRectF rect)
{
curRect = rect;
//使其在鼠標未點擊也能響應(yīng)懸停事件
setAcceptHoverEvents(true);
}
ImgShow::~ImgShow()
{
}
void ImgShow::UpdateImageRect(QRectF rect)
{
mtx.lock();
curRect = rect;
mtx.unlock();
}
void ImgShow::UpdateImageShow(QPixmap pix)
{
mtx.lock();
curPix = pix;
mtx.unlock();
// 設(shè)置玩圖像數(shù)據(jù)后刷新圖像
QGraphicsView * view = this->scene()->views().at(0);
view->viewport()->update();
}
QRectF ImgShow::boundingRect() const
{
return curRect;
}
void ImgShow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
mtx.lock();
// painter->drawPixmap(-static_cast<int>(curRect.width() / 2), -static_cast<int>(curRect.height() / 2), curPix);
//上面的drawPixmap起始位置不太一樣
painter->drawPixmap(curRect.toRect(), curPix);
qDebug()<< curRect.width() << curRect.height();
mtx.unlock();
}
void ImgShow::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
{
QPointF localPos = event->pos(); // 當前鼠標位置相對于圖元坐標系的坐標
QRectF imageRect = mapRectToScene(boundingRect()); // 圖像有效區(qū)域在場景中的位置
QPointF globalPos = scenePos() + localPos - imageRect.topLeft(); // 轉(zhuǎn)換為圖像有效區(qū)域的全局坐標
qDebug()<< globalPos;
}
//scenePos()為圖元在場景的坐標,因此 scenePos() + localPos 為鼠標在場景坐標系的坐標
//imageRect.topLeft()為圖像有效區(qū)域的左上角在圖元坐標系的位置,因此 localPos - imageRect.topLeft() 為當前鼠標事件在圖片局部坐標系中的位置
當圖像的有效區(qū)域并不是鋪滿圖元時,就可以用該方式得到,當前鼠標位置對于圖像有效區(qū)域的全局坐標
到了這里,關(guān)于Qt QGraphicsItem獲取鼠標位置對應(yīng)圖像坐標的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!