Using as reference my previous posts on this subject:
I was able to assemble a quick C++/Qt/OpenCV demo that creates an OpenCV window and writes a message on the console every time the left mouse button is pressed.
I believe the code is self-explanatory:
main.cpp:
#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <QtWidgets/QApplication>
void on_mouse(int event, int x, int y, int flags, void* param)
{
if (event == CV_EVENT_LBUTTONDOWN)
{
std::cout << "@ Left mouse button pressed at: " << x << "," << y << std::endl;
}
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
IplImage* img = cvLoadImage("/Users/karlphillip/workspace/opencv/qt_mouse/LeafGlyph.jpg");
if (!img)
{
std::cout << "!!! Failed to load image" << std::endl;
return -1;
}
cvNamedWindow("result", CV_WINDOW_AUTOSIZE);
cvSetMouseCallback("result",&on_mouse, 0);
cvShowImage("result", img);
cvWaitKey(0);
return app.exec();
}
project.pro (used on Mac OS X):
TEMPLATE = app
QT += widgets
## OpenCV settings for Mac OS X
macx {
INCLUDEPATH += /usr/local/include/opencv
LIBS += -L/usr/local/lib/ \
-lopencv_core \
-lopencv_highgui \
-lopencv_imgproc
}
SOURCES += \
main.cpp
Notes about your implementation:
I suggest you move the call to cvSetMouseCallback()
to wherever you are calling cvNamedWindow()
. I suspect that the right place to do it is in the constructor of MainWindow
which should create the window, right?! Then you would also have to define on_mouse()
as a static member of MainWindow
and implement it.
If you do that your code would be similar to:
void MainWindow::on_mouse(int event, int x, int y, int flags, void* param)
{
if (event == CV_EVENT_LBUTTONDOWN)
{
std::cout << "@ Left mouse button pressed at: " << x << "," << y << std::endl;
}
}
MainWindow::MainWindow()
{
IplImage* img = cvLoadImage("/Users/karlphillip/workspace/opencv/qt_mouse/LeafGlyph.jpg");
if (!img)
{
std::cout << "!!! Failed to load image" << std::endl;
return;
}
cvNamedWindow("result", CV_WINDOW_AUTOSIZE);
cvSetMouseCallback("result",&on_mouse, 0);
cvShowImage("result", img);
cvWaitKey(0);
}