【问题标题】:How to draw a frame over an image hovered如何在悬停的图像上绘制框架
【发布时间】:2015-09-02 06:56:39
【问题描述】:

我在考虑标题,因为我遇到了如何命名的问题。我正在使用 Qt 和 C++ 编程,我可以清楚地使用基本结构。现在我想做一些更有效的事情,但我不知道什么是最好的解决方案。所以我在主窗口中有一个图像。我该如何解决:

如果我将鼠标光标移动到图像的特定区域,则程序应在该区域周围绘制黄色框。如果我将鼠标移动到该图像的其他部分,则该框架应该消失。在伪代码中:

if(mouse_X >= 100 && mouse_X <=150 && 
     mouse_Y >= 250 && mouse_Y <= 300)
    drawFrame();

有什么建议吗?

【问题讨论】:

  • 安装一个event filter,它的作用与您的伪代码几乎完全一样。
  • 不喜欢这些欺骗目标,他们不回答问题。似乎没有一个规范的 How to install an event filter in Qt 问题并给出了不错的答案。
  • 您应该更准确地了解您当前的情况,特别是您使用哪个小部件来显示该图像?因为可能已经有一个可以使用的信号了。

标签: c++ qt


【解决方案1】:

有很多方法可以解决这个问题。

其中一个可能是使用您的问题中所述的@nwp 事件过滤器。但也有必要跟踪图像中的鼠标移动。

我不知道您是如何加载图像的,所以下面的代码只是一个示例,假设您在 QLabel 中加载图像。你必须使这个想法适应你自己的项目。

ma​​in.cpp

#include "mywindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MyWindow myWindow;
    myWindow.show();
    return app.exec();
}

mywindow.h

#ifndef _MAINWINDOW_H
#define _MAINWINDOW_H

#include <QMainWindow>
#include <QLabel>
#include <QDebug>

class MyWindow: public QWidget {
    Q_OBJECT    

public:
    MyWindow();
    ~MyWindow();
    bool eventFilter(QObject *object, QEvent *event);

private:
    QLabel *imageLabel;
};

#endif

mywindow.cpp

#include "mywindow.h"
#include <QPixmap>
#include <QEvent>
#include <QMouseEvent>

MyWindow::MyWindow()
{
    imageLabel = new QLabel(this);
    imageLabel->setPixmap(QPixmap(":icon"));
    imageLabel->resize(imageLabel->pixmap()->size());
    qDebug() << imageLabel->pixmap()->size();

    imageLabel->setMouseTracking(true);
    imageLabel->installEventFilter(this);
}

MyWindow::~MyWindow()
{
}

bool MyWindow::eventFilter(QObject *object, QEvent *event)
{
    if (object == imageLabel && event->type() == QEvent::MouseMove) {
        /*
         * We know the image is 60x60 px.
         */
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if(mouseEvent->x() >= 0 && mouseEvent->x() <=30 &&
           mouseEvent->y() >= 0 && mouseEvent->y() <= 30)
        {
            qDebug() << "drawFrame()";
        } else {
            qDebug() << "!drawFrame()";
        }
        return false;
    }

    return false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多