1 //IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
3 // By downloading, copying, installing or using the software you agree to this license.
4 // If you do not agree to this license, do not download, install,
5 // copy or use the software.
9 // For Open Source Computer Vision Library
11 //Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
12 //Copyright (C) 2008-2010, Willow Garage Inc., all rights reserved.
13 //Third party copyrights are property of their respective owners.
15 //Redistribution and use in source and binary forms, with or without modification,
16 //are permitted provided that the following conditions are met:
18 // * Redistribution's of source code must retain the above copyright notice,
19 // this list of conditions and the following disclaimer.
21 // * Redistribution's in binary form must reproduce the above copyright notice,
22 // this list of conditions and the following disclaimer in the documentation
23 // and/or other materials provided with the distribution.
25 // * The name of the copyright holders may not be used to endorse or promote products
26 // derived from this software without specific prior written permission.
28 //This software is provided by the copyright holders and contributors "as is" and
29 //any express or implied warranties, including, but not limited to, the implied
30 //warranties of merchantability and fitness for a particular purpose are disclaimed.
31 //In no event shall the Intel Corporation or contributors be liable for any direct,
32 //indirect, incidental, special, exemplary, or consequential damages
33 //(including, but not limited to, procurement of substitute goods or services;
34 //loss of use, data, or profits; or business interruption) however caused
35 //and on any theory of liability, whether in contract, strict liability,
36 //or tort (including negligence or otherwise) arising in any way out of
37 //the use of this software, even if advised of the possibility of such damage.
39 //--------------------Google Code 2010 -- Yannick Verdie--------------------//
41 #include "precomp.hpp"
47 #include <window_QT.h>
64 //Static and global first
65 static GuiReceiver *guiMainThread = NULL;
66 static int parameterSystemC = 1;
67 static char* parameterSystemV[] = {(char*)""};
68 static bool multiThreads = false;
69 static int last_key = -1;
70 QWaitCondition key_pressed;
72 static const unsigned int threshold_zoom_img_region = 30;
73 //the minimum zoom value to start displaying the values in the grid
74 //that is also the number of pixel per grid
76 static CvWinProperties* global_control_panel = NULL;
77 //end static and global
80 Qt::ConnectionType autoBlockingConnection();
82 // Implementation - this allows us to do blocking whilst automatically selecting the right
83 // behaviour for in-thread and out-of-thread launches of cv windows. Qt strangely doesn't
84 // cater for this, but does for strictly queued connections.
85 Qt::ConnectionType autoBlockingConnection() {
86 return (QThread::currentThread() != QApplication::instance()->thread())
87 ? Qt::BlockingQueuedConnection
88 : Qt::DirectConnection;
91 CV_IMPL CvFont cvFontQt(const char* nameFont, int pointSize,CvScalar color,int weight,int style, int spacing)
95 //CvScalar color <- only Qt (blue_component, green_component, red\_component[, alpha_component])
96 int font_face;//<- style in Qt
100 float hscale, vscale;
102 int thickness;//<- weight in Qt
103 float dx;//spacing letter in Qt (0 default) in pixel
104 int line_type;//<- pointSize in Qt
106 CvFont f = {nameFont,color,style,NULL,NULL,NULL,0,0,0,weight,spacing,pointSize};
111 CV_IMPL void cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont* font)
114 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
116 QMetaObject::invokeMethod(guiMainThread,
118 autoBlockingConnection(),
119 Q_ARG(void*, (void*) img),
120 Q_ARG(QString,QString(text)),
121 Q_ARG(QPoint, QPoint(org.x,org.y)),
122 Q_ARG(void*,(void*) font));
126 double cvGetRatioWindow_QT(const char* name)
129 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
132 QMetaObject::invokeMethod(guiMainThread,
134 autoBlockingConnection(),
135 Q_RETURN_ARG(double, result),
136 Q_ARG(QString, QString(name)));
142 void cvSetRatioWindow_QT(const char* name,double prop_value)
146 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
148 QMetaObject::invokeMethod(guiMainThread,
150 autoBlockingConnection(),
151 Q_ARG(QString, QString(name)),
152 Q_ARG(double, prop_value));
156 double cvGetPropWindow_QT(const char* name)
159 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
162 QMetaObject::invokeMethod(guiMainThread,
164 autoBlockingConnection(),
165 Q_RETURN_ARG(double, result),
166 Q_ARG(QString, QString(name)));
172 void cvSetPropWindow_QT(const char* name,double prop_value)
175 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
177 QMetaObject::invokeMethod(guiMainThread,
179 autoBlockingConnection(),
180 Q_ARG(QString, QString(name)),
181 Q_ARG(double, prop_value));
184 void cv::setWindowTitle(const String& winname, const String& title)
187 CV_Error(Error::StsNullPtr, "NULL guiReceiver (please create a window)");
189 QMetaObject::invokeMethod(guiMainThread,
191 autoBlockingConnection(),
192 Q_ARG(QString, QString(winname.c_str())),
193 Q_ARG(QString, QString(title.c_str())));
197 void cvSetModeWindow_QT(const char* name, double prop_value)
200 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
202 QMetaObject::invokeMethod(guiMainThread,
204 autoBlockingConnection(),
205 Q_ARG(QString, QString(name)),
206 Q_ARG(double, prop_value));
210 double cvGetModeWindow_QT(const char* name)
213 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
217 QMetaObject::invokeMethod(guiMainThread,
219 autoBlockingConnection(),
220 Q_RETURN_ARG(double, result),
221 Q_ARG(QString, QString(name)));
227 CV_IMPL void cvDisplayOverlay(const char* name, const char* text, int delayms)
230 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
232 QMetaObject::invokeMethod(guiMainThread,
234 autoBlockingConnection(),
235 Q_ARG(QString, QString(name)),
236 Q_ARG(QString, QString(text)),
237 Q_ARG(int, delayms));
241 CV_IMPL void cvSaveWindowParameters(const char* name)
244 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
246 QMetaObject::invokeMethod(guiMainThread,
247 "saveWindowParameters",
248 autoBlockingConnection(),
249 Q_ARG(QString, QString(name)));
253 CV_IMPL void cvLoadWindowParameters(const char* name)
256 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
258 QMetaObject::invokeMethod(guiMainThread,
259 "loadWindowParameters",
260 autoBlockingConnection(),
261 Q_ARG(QString, QString(name)));
265 CV_IMPL void cvDisplayStatusBar(const char* name, const char* text, int delayms)
268 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
270 QMetaObject::invokeMethod(guiMainThread,
272 autoBlockingConnection(),
273 Q_ARG(QString, QString(name)),
274 Q_ARG(QString, QString(text)),
275 Q_ARG(int, delayms));
279 CV_IMPL int cvWaitKey(int delay)
286 unsigned long delayms = delay <= 0 ? ULONG_MAX : delay; //in milliseconds
291 if (key_pressed.wait(&mutexKey, delayms)) //false if timeout
300 //cannot use wait here because events will not be distributed before processEvents (the main eventLoop is broken)
301 //so I create a Thread for the QTimer
304 guiMainThread->timer->start(delay);
308 while (!guiMainThread->bTimeOut)
310 qApp->processEvents(QEventLoop::AllEvents);
312 if (!guiMainThread)//when all the windows are deleted
320 guiMainThread->timer->stop();
321 //printf("keypressed\n");
332 * //will not work, I broke the event loop !!!!
334 QWaitCondition waitCondition;
335 waitCondition.wait(&dummy, 2);
338 //to decrease CPU usage
339 //sleep 1 millisecond
340 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
348 guiMainThread->bTimeOut = false;
355 //This function is experimental and some functions (such as cvSet/getWindowProperty will not work)
356 //We recommend not using this function for now
357 CV_IMPL int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[])
360 QFuture<int> future = QtConcurrent::run(pt2Func, argc, argv);
361 return guiMainThread->start();
365 CV_IMPL void cvStopLoop()
371 static CvWindow* icvFindWindowByName(QString name)
373 CvWindow* window = 0;
375 //This is not a very clean way to do the stuff. Indeed, QAction automatically generate toolTil (QLabel)
376 //that can be grabbed here and crash the code at 'w->param_name==name'.
377 foreach (QWidget* widget, QApplication::topLevelWidgets())
379 if (widget->isWindow() && !widget->parentWidget())//is a window without parent
381 CvWinModel* temp = (CvWinModel*) widget;
383 if (temp->type == type_CvWindow)
385 CvWindow* w = (CvWindow*) temp;
386 if (w->objectName() == name)
399 static CvBar* icvFindBarByName(QBoxLayout* layout, QString name_bar, typeBar type)
404 int stop_index = layout->layout()->count();
406 for (int i = 0; i < stop_index; ++i)
408 CvBar* t = (CvBar*) layout->layout()->itemAt(i);
410 if (t->type == type && t->name_bar == name_bar)
418 static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char* name_window, QBoxLayout* layout = NULL)
420 QString nameQt(name_trackbar);
421 if ((!name_window || !name_window[0]) && global_control_panel) //window name is null and we have a control panel
422 layout = global_control_panel->myLayout;
426 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(name_window));
429 CV_Error(CV_StsNullPtr, "NULL window handler");
431 if (w->param_gui_mode == CV_GUI_NORMAL)
432 return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
434 if (w->param_gui_mode == CV_GUI_EXPANDED)
436 CvBar* result = icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
439 return (CvTrackbar*) result;
441 return (CvTrackbar*) icvFindBarByName(global_control_panel->myLayout, nameQt, type_CvTrackbar);
448 //layout was specified
449 return (CvTrackbar*) icvFindBarByName(layout, nameQt, type_CvTrackbar);
454 static CvButtonbar* icvFindButtonBarByName(const char* button_name, QBoxLayout* layout)
456 QString nameQt(button_name);
457 return (CvButtonbar*) icvFindBarByName(layout, nameQt, type_CvButtonbar);
461 static int icvInitSystem(int* c, char** v)
463 //"For any GUI application using Qt, there is precisely one QApplication object"
464 if (!QApplication::instance())
466 new QApplication(*c, v);
468 qDebug() << "init done";
470 #ifdef HAVE_QT_OPENGL
471 qDebug() << "opengl support available";
479 CV_IMPL int cvInitSystem(int, char**)
481 icvInitSystem(¶meterSystemC, parameterSystemV);
486 CV_IMPL int cvNamedWindow(const char* name, int flags)
489 guiMainThread = new GuiReceiver;
490 if (QThread::currentThread() != QApplication::instance()->thread()) {
492 QMetaObject::invokeMethod(guiMainThread,
494 Qt::BlockingQueuedConnection, // block so that we can do useful stuff once we confirm it is created
495 Q_ARG(QString, QString(name)),
498 guiMainThread->createWindow(QString(name), flags);
501 return 1; //Dummy value - probably should return the result of the invocation.
505 CV_IMPL void cvDestroyWindow(const char* name)
508 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
510 QMetaObject::invokeMethod(guiMainThread,
512 Qt::AutoConnection, // if another thread is controlling, let it handle it without blocking ourselves here
513 Q_ARG(QString, QString(name)));
517 CV_IMPL void cvDestroyAllWindows()
521 QMetaObject::invokeMethod(guiMainThread,
523 Qt::AutoConnection // if another thread is controlling, let it handle it without blocking ourselves here
528 CV_IMPL void* cvGetWindowHandle(const char* name)
531 CV_Error( CV_StsNullPtr, "NULL name string" );
533 return (void*) icvFindWindowByName(QLatin1String(name));
537 CV_IMPL const char* cvGetWindowName(void* window_handle)
540 CV_Error( CV_StsNullPtr, "NULL window handler" );
542 return ((CvWindow*)window_handle)->objectName().toLatin1().data();
546 CV_IMPL void cvMoveWindow(const char* name, int x, int y)
549 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
550 QMetaObject::invokeMethod(guiMainThread,
552 autoBlockingConnection(),
553 Q_ARG(QString, QString(name)),
558 CV_IMPL void cvResizeWindow(const char* name, int width, int height)
561 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
562 QMetaObject::invokeMethod(guiMainThread,
564 autoBlockingConnection(),
565 Q_ARG(QString, QString(name)),
571 CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata)
574 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
576 QMetaObject::invokeMethod(guiMainThread,
578 autoBlockingConnection(),
579 Q_ARG(QString, QString(name_bar)),
580 Q_ARG(QString, QString(window_name)),
581 Q_ARG(void*, (void*)val),
583 Q_ARG(void*, (void*)on_notify),
584 Q_ARG(void*, (void*)userdata));
586 return 1; //dummy value
590 CV_IMPL int cvStartWindowThread()
596 CV_IMPL int cvCreateTrackbar(const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change)
599 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
601 QMetaObject::invokeMethod(guiMainThread,
603 autoBlockingConnection(),
604 Q_ARG(QString, QString(name_bar)),
605 Q_ARG(QString, QString(window_name)),
606 Q_ARG(void*, (void*)value),
608 Q_ARG(void*, (void*)on_change));
610 return 1; //dummy value
614 CV_IMPL int cvCreateButton(const char* button_name, CvButtonCallback on_change, void* userdata, int button_type, int initial_button_state)
617 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
619 if (initial_button_state < 0 || initial_button_state > 1)
622 QMetaObject::invokeMethod(guiMainThread,
624 autoBlockingConnection(),
625 Q_ARG(QString, QString(button_name)),
626 Q_ARG(int, button_type),
627 Q_ARG(int, initial_button_state),
628 Q_ARG(void*, (void*)on_change),
629 Q_ARG(void*, userdata));
631 return 1;//dummy value
635 CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name)
639 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
642 result = t->slider->value();
648 CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int pos)
650 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
653 t->slider->setValue(pos);
657 /* assign callback for mouse events */
658 CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param)
660 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
663 CV_Error(CV_StsNullPtr, "NULL window handler");
665 w->setMouseCallBack(on_mouse, param);
670 CV_IMPL void cvShowImage(const char* name, const CvArr* arr)
673 guiMainThread = new GuiReceiver;
674 if (QThread::currentThread() != QApplication::instance()->thread()) {
676 QMetaObject::invokeMethod(guiMainThread,
678 autoBlockingConnection(),
679 Q_ARG(QString, QString(name)),
680 Q_ARG(void*, (void*)arr)
683 guiMainThread->showImage(QString(name), (void*)arr);
688 #ifdef HAVE_QT_OPENGL
690 CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
693 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
695 QMetaObject::invokeMethod(guiMainThread,
696 "setOpenGlDrawCallback",
697 autoBlockingConnection(),
698 Q_ARG(QString, QString(window_name)),
699 Q_ARG(void*, (void*)callback),
700 Q_ARG(void*, userdata));
704 CV_IMPL void cvSetOpenGlContext(const char* window_name)
707 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
709 QMetaObject::invokeMethod(guiMainThread,
711 autoBlockingConnection(),
712 Q_ARG(QString, QString(window_name)));
716 CV_IMPL void cvUpdateWindow(const char* window_name)
719 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
721 QMetaObject::invokeMethod(guiMainThread,
723 autoBlockingConnection(),
724 Q_ARG(QString, QString(window_name)));
730 double cvGetOpenGlProp_QT(const char* name)
736 QMetaObject::invokeMethod(guiMainThread,
738 autoBlockingConnection(),
739 Q_RETURN_ARG(double, result),
740 Q_ARG(QString, QString(name)));
747 //////////////////////////////////////////////////////
751 GuiReceiver::GuiReceiver() : bTimeOut(false), nb_windows(0)
753 doesExternalQAppExist = (QApplication::instance() != 0);
754 icvInitSystem(¶meterSystemC, parameterSystemV);
756 timer = new QTimer(this);
757 QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
758 timer->setSingleShot(true);
759 if ( doesExternalQAppExist ) {
760 moveToThread(QApplication::instance()->thread());
765 void GuiReceiver::isLastWindow()
767 if (--nb_windows <= 0)
769 delete guiMainThread;//delete global_control_panel too
770 guiMainThread = NULL;
772 if (!doesExternalQAppExist)
780 GuiReceiver::~GuiReceiver()
782 if (global_control_panel)
784 delete global_control_panel;
785 global_control_panel = NULL;
790 void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2)
795 mat = cvGetMat(arr, &stub);
797 int nbChannelOriginImage = cvGetElemType(mat);
798 if (nbChannelOriginImage != CV_8UC3) return; //for now, font works only with 8UC3
800 QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888);
802 CvFont* font = (CvFont*)arg2;
807 QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/);
808 f.setStyle((QFont::Style) font->font_face/*style*/);
809 f.setLetterSpacing(QFont::AbsoluteSpacing, font->dx/*spacing*/);
810 //cvScalar(blue_component, green_component, red_component[, alpha_component])
811 //Qt map non-transparent to 0xFF and transparent to 0
812 //OpenCV scalar is the reverse, so 255-font->color.val[3]
813 qp.setPen(QColor(font->color.val[2], font->color.val[1], font->color.val[0], 255 - font->color.val[3]));
816 qp.drawText(org, text);
821 void GuiReceiver::saveWindowParameters(QString name)
823 QPointer<CvWindow> w = icvFindWindowByName(name);
830 void GuiReceiver::loadWindowParameters(QString name)
832 QPointer<CvWindow> w = icvFindWindowByName(name);
839 double GuiReceiver::getRatioWindow(QString name)
841 QPointer<CvWindow> w = icvFindWindowByName(name);
846 return w->getRatio();
850 void GuiReceiver::setRatioWindow(QString name, double arg2)
852 QPointer<CvWindow> w = icvFindWindowByName( name.toLatin1().data() );
857 int flags = (int) arg2;
863 double GuiReceiver::getPropWindow(QString name)
865 QPointer<CvWindow> w = icvFindWindowByName(name);
870 return (double) w->getPropWindow();
874 void GuiReceiver::setPropWindow(QString name, double arg2)
876 QPointer<CvWindow> w = icvFindWindowByName(name);
881 int flags = (int) arg2;
883 w->setPropWindow(flags);
886 void GuiReceiver::setWindowTitle(QString name, QString title)
888 QPointer<CvWindow> w = icvFindWindowByName(name);
892 cvNamedWindow(name.toLatin1().data());
893 w = icvFindWindowByName(name);
899 w->setWindowTitle(title);
903 double GuiReceiver::isFullScreen(QString name)
905 QPointer<CvWindow> w = icvFindWindowByName(name);
910 return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL;
914 void GuiReceiver::toggleFullScreen(QString name, double arg2)
916 QPointer<CvWindow> w = icvFindWindowByName(name);
921 int flags = (int) arg2;
923 w->toggleFullScreen(flags);
927 void GuiReceiver::createWindow(QString name, int flags)
930 CV_Error(CV_StsNullPtr, "NULL session handler" );
932 // Check the name in the storage
933 if (icvFindWindowByName(name.toLatin1().data()))
939 new CvWindow(name, flags);
943 void GuiReceiver::timeOut()
949 void GuiReceiver::displayInfo(QString name, QString text, int delayms)
951 QPointer<CvWindow> w = icvFindWindowByName(name);
954 w->displayInfo(text, delayms);
958 void GuiReceiver::displayStatusBar(QString name, QString text, int delayms)
960 QPointer<CvWindow> w = icvFindWindowByName(name);
963 w->displayStatusBar(text, delayms);
967 void GuiReceiver::showImage(QString name, void* arr)
969 QPointer<CvWindow> w = icvFindWindowByName(name);
971 if (!w) //as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null
973 cvNamedWindow(name.toLatin1().data());
974 w = icvFindWindowByName(name);
978 return; // keep silence here.
984 mat = cvGetMat(arr, &stub);
986 cv::Mat im = cv::cvarrToMat(mat);
987 cv::imshow(name.toUtf8().data(), im);
999 void GuiReceiver::destroyWindow(QString name)
1002 QPointer<CvWindow> w = icvFindWindowByName(name);
1008 //in not-multiThreads mode, looks like the window is hidden but not deleted
1009 //so I do it manually
1010 //otherwise QApplication do it for me if the exec command was executed (in multiThread mode)
1017 void GuiReceiver::destroyAllWindow()
1020 CV_Error(CV_StsNullPtr, "NULL session handler" );
1024 // WARNING: this could even close windows from an external parent app
1025 //#TODO check externalQAppExists and in case it does, close windows carefully,
1026 // i.e. apply the className-check from below...
1027 qApp->closeAllWindows();
1031 bool isWidgetDeleted = true;
1032 while(isWidgetDeleted)
1034 isWidgetDeleted = false;
1035 QWidgetList list = QApplication::topLevelWidgets();
1036 for (int i = 0; i < list.count(); i++)
1038 QObject *obj = list.at(i);
1039 if (obj->metaObject()->className() == QString("CvWindow"))
1042 isWidgetDeleted = true;
1051 void GuiReceiver::moveWindow(QString name, int x, int y)
1053 QPointer<CvWindow> w = icvFindWindowByName(name);
1060 void GuiReceiver::resizeWindow(QString name, int width, int height)
1062 QPointer<CvWindow> w = icvFindWindowByName(name);
1067 w->setViewportSize(QSize(width, height));
1072 void GuiReceiver::enablePropertiesButtonEachWindow()
1074 //For each window, enable window property button
1075 foreach (QWidget* widget, QApplication::topLevelWidgets())
1077 if (widget->isWindow() && !widget->parentWidget()) //is a window without parent
1079 CvWinModel* temp = (CvWinModel*) widget;
1080 if (temp->type == type_CvWindow)
1082 CvWindow* w = (CvWindow*) widget;
1084 //active window properties button
1085 w->enablePropertiesButton();
1092 void GuiReceiver::addButton(QString button_name, int button_type, int initial_button_state, void* on_change, void* userdata)
1094 if (!global_control_panel)
1097 QPointer<CvButtonbar> b;
1099 if (global_control_panel->myLayout->count() == 0) //if that is the first button attach to the control panel, create a new button bar
1101 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1102 enablePropertiesButtonEachWindow();
1107 CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count() - 1);
1109 if (lastbar->type == type_CvTrackbar) //if last bar is a trackbar, create a new buttonbar, else, attach to the current bar
1110 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1112 b = (CvButtonbar*) lastbar;
1116 b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state);
1120 void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata)
1122 QBoxLayout *layout = NULL;
1123 QPointer<CvWindow> w;
1125 if (!window_name.isEmpty())
1127 w = icvFindWindowByName(window_name);
1134 if (global_control_panel)
1135 layout = global_control_panel->myLayout;
1138 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1140 if (t) //trackbar exists
1144 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1146 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1147 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1149 CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
1153 void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change)
1155 QBoxLayout *layout = NULL;
1156 QPointer<CvWindow> w;
1158 if (!window_name.isEmpty())
1160 w = icvFindWindowByName(window_name);
1167 if (global_control_panel)
1168 layout = global_control_panel->myLayout;
1171 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1173 if (t) //trackbar exists
1177 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1179 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1180 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1182 CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
1186 int GuiReceiver::start()
1188 return qApp->exec();
1192 void GuiReceiver::setOpenGlDrawCallback(QString name, void* callback, void* userdata)
1194 QPointer<CvWindow> w = icvFindWindowByName(name);
1197 w->setOpenGlDrawCallback((CvOpenGlDrawCallback) callback, userdata);
1200 void GuiReceiver::setOpenGlContext(QString name)
1202 QPointer<CvWindow> w = icvFindWindowByName(name);
1205 w->makeCurrentOpenGlContext();
1208 void GuiReceiver::updateWindow(QString name)
1210 QPointer<CvWindow> w = icvFindWindowByName(name);
1216 double GuiReceiver::isOpenGl(QString name)
1220 QPointer<CvWindow> w = icvFindWindowByName(name);
1223 result = (double) w->isOpenGl();
1229 //////////////////////////////////////////////////////
1233 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)
1236 callback2 = on_change;
1239 create(arg, name, value, _count);
1243 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)
1245 callback = on_change;
1249 create(arg, name, value, _count);
1253 void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)
1255 type = type_CvTrackbar;
1258 setObjectName(name_bar);
1261 slider = new QSlider(Qt::Horizontal);
1262 slider->setFocusPolicy(Qt::StrongFocus);
1263 slider->setMinimum(0);
1264 slider->setMaximum(_count);
1265 slider->setPageStep(5);
1266 slider->setValue(*value);
1267 slider->setTickPosition(QSlider::TicksBelow);
1270 //Change style of the Slider
1271 //slider->setStyleSheet(str_Trackbar_css);
1273 QFile qss(":/stylesheet-trackbar");
1274 if (qss.open(QFile::ReadOnly))
1276 slider->setStyleSheet(QLatin1String(qss.readAll()));
1281 //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?)
1282 //slider->setTickPosition(QSlider::TicksBelow);
1283 label = new QPushButton;
1284 label->setFlat(true);
1285 setLabel(slider->value());
1288 QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(update(int)));
1290 QObject::connect(label, SIGNAL(clicked()), this, SLOT(createDialog()));
1292 //label->setStyleSheet("QPushButton:disabled {color: black}");
1294 addWidget(label, Qt::AlignLeft);//name + value
1295 addWidget(slider, Qt::AlignCenter);//slider
1299 void CvTrackbar::createDialog()
1303 //crash if I access the values directly and give them to QInputDialog, so do a copy first.
1304 int value = slider->value();
1305 int step = slider->singleStep();
1306 int min = slider->minimum();
1307 int max = slider->maximum();
1310 #if QT_VERSION >= 0x040500
1311 QInputDialog::getInt
1313 QInputDialog::getInteger
1315 (this->parentWidget(),
1316 tr("Slider %1").arg(name_bar),
1325 slider->setValue(i);
1329 void CvTrackbar::update(int myvalue)
1333 *dataSlider = myvalue;
1342 callback2(myvalue, userdata);
1348 void CvTrackbar::setLabel(int myvalue)
1350 QString nameNormalized = name_bar.leftJustified( 10, ' ', true );
1351 QString valueMaximum = QString("%1").arg(slider->maximum());
1352 QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum);
1353 label->setText(str);
1357 //////////////////////////////////////////////////////
1361 //here CvButtonbar class
1362 CvButtonbar::CvButtonbar(QWidget* arg, QString arg2)
1364 type = type_CvButtonbar;
1367 setObjectName(name_bar);
1369 group_button = new QButtonGroup(this);
1373 void CvButtonbar::setLabel()
1375 QString nameNormalized = name_bar.leftJustified(10, ' ', true);
1376 label->setText(nameNormalized);
1380 void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state)
1382 QString button_name = name;
1384 if (button_name == "")
1385 button_name = tr("button %1").arg(this->count());
1387 QPointer<QAbstractButton> button;
1389 if (button_type == CV_PUSH_BUTTON)
1390 button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata);
1392 if (button_type == CV_CHECKBOX)
1393 button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state);
1395 if (button_type == CV_RADIOBOX)
1397 button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state);
1398 group_button->addButton(button);
1403 if (button_type == CV_PUSH_BUTTON)
1404 QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool)));
1406 QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool)));
1408 addWidget(button, Qt::AlignCenter);
1413 //////////////////////////////////////////////////////
1418 CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4)
1425 setObjectName(button_name);
1426 setText(button_name);
1433 void CvPushButton::callCallBack(bool checked)
1436 callback(checked, userdata);
1440 CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1447 setObjectName(button_name);
1448 setCheckState((initial_button_state == 1 ? Qt::Checked : Qt::Unchecked));
1449 setText(button_name);
1456 void CvCheckBox::callCallBack(bool checked)
1459 callback(checked, userdata);
1463 CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1470 setObjectName(button_name);
1471 setChecked(initial_button_state);
1472 setText(button_name);
1478 void CvRadioButton::callCallBack(bool checked)
1481 callback(checked, userdata);
1485 //////////////////////////////////////////////////////
1489 //here CvWinProperties class
1490 CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)
1492 //setParent(parent);
1493 type = type_CvWinProperties;
1494 setWindowFlags(Qt::Tool);
1495 setContentsMargins(0, 0, 0, 0);
1496 setWindowTitle(name_paraWindow);
1497 setObjectName(name_paraWindow);
1500 myLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1501 myLayout->setObjectName(QString::fromUtf8("boxLayout"));
1502 myLayout->setContentsMargins(0, 0, 0, 0);
1503 myLayout->setSpacing(0);
1504 myLayout->setMargin(0);
1505 myLayout->setSizeConstraint(QLayout::SetFixedSize);
1506 setLayout(myLayout);
1512 void CvWinProperties::closeEvent(QCloseEvent* e)
1514 e->accept(); //intersept the close event (not sure I really need it)
1515 //an hide event is also sent. I will intercept it and do some processing
1519 void CvWinProperties::showEvent(QShowEvent* evnt)
1521 //why -1,-1 ?: do this trick because the first time the code is run,
1522 //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).
1523 //then hide will save the last position and thus, we want to retreive it (event accepted).
1524 QPoint mypos(-1, -1);
1525 QSettings settings("OpenCV2", objectName());
1526 mypos = settings.value("pos", mypos).toPoint();
1540 void CvWinProperties::hideEvent(QHideEvent* evnt)
1542 QSettings settings("OpenCV2", objectName());
1543 settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)
1548 CvWinProperties::~CvWinProperties()
1550 //clear the setting pos
1551 QSettings settings("OpenCV2", objectName());
1552 settings.remove("pos");
1556 //////////////////////////////////////////////////////
1560 CvWindow::CvWindow(QString name, int arg2)
1562 type = type_CvWindow;
1564 param_flags = arg2 & 0x0000000F;
1565 param_gui_mode = arg2 & 0x000000F0;
1566 param_ratio_mode = arg2 & 0x00000F00;
1568 //setAttribute(Qt::WA_DeleteOnClose); //in other case, does not release memory
1569 setContentsMargins(0, 0, 0, 0);
1570 setWindowTitle(name);
1571 setObjectName(name);
1573 setFocus( Qt::PopupFocusReason ); //#1695 arrow keys are not received without the explicit focus
1576 setMinimumSize(1, 1);
1578 //1: create control panel
1579 if (!global_control_panel)
1580 global_control_panel = createParameterWindow();
1584 createGlobalLayout();
1587 #ifndef HAVE_QT_OPENGL
1588 if (arg2 & CV_WINDOW_OPENGL)
1589 CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
1590 mode_display = CV_MODE_NORMAL;
1592 mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
1593 if (mode_display == CV_MODE_OPENGL)
1594 param_gui_mode = CV_GUI_NORMAL;
1598 //4: shortcuts and actions
1599 //5: toolBar and statusbar
1600 if (param_gui_mode == CV_GUI_EXPANDED)
1609 //Now attach everything
1611 myGlobalLayout->addWidget(myToolBar, Qt::AlignCenter);
1613 myGlobalLayout->addWidget(myView->getWidget(), Qt::AlignCenter);
1615 myGlobalLayout->addLayout(myBarLayout, Qt::AlignCenter);
1618 myGlobalLayout->addWidget(myStatusBar, Qt::AlignCenter);
1620 setLayout(myGlobalLayout);
1625 CvWindow::~CvWindow()
1628 guiMainThread->isLastWindow();
1632 void CvWindow::setMouseCallBack(CvMouseCallback callback, void* param)
1634 myView->setMouseCallBack(callback, param);
1638 void CvWindow::writeSettings()
1640 //organisation and application's name
1641 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1643 settings.setValue("pos", pos());
1644 settings.setValue("size", size());
1645 settings.setValue("mode_resize" ,param_flags);
1646 settings.setValue("mode_gui", param_gui_mode);
1648 myView->writeSettings(settings);
1650 icvSaveTrackbars(&settings);
1652 if (global_control_panel)
1654 icvSaveControlPanel();
1655 settings.setValue("posPanel", global_control_panel->pos());
1661 //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars)
1662 void CvWindow::readSettings()
1664 //organisation and application's name
1665 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1667 QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();
1668 QSize _size = settings.value("size", QSize(400, 400)).toSize();
1670 param_flags = settings.value("mode_resize", param_flags).toInt();
1671 param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();
1673 param_flags = settings.value("mode_resize", param_flags).toInt();
1675 myView->readSettings(settings);
1678 icvLoadTrackbars(&settings);
1683 if (global_control_panel)
1685 icvLoadControlPanel();
1686 global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint());
1691 double CvWindow::getRatio()
1693 return myView->getRatio();
1697 void CvWindow::setRatio(int flags)
1699 myView->setRatio(flags);
1703 int CvWindow::getPropWindow()
1709 void CvWindow::setPropWindow(int flags)
1711 if (param_flags == flags) //nothing to do
1716 case CV_WINDOW_NORMAL:
1717 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1718 param_flags = flags;
1722 case CV_WINDOW_AUTOSIZE:
1723 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1724 param_flags = flags;
1733 void CvWindow::toggleFullScreen(int flags)
1735 if (isFullScreen() && flags == CV_WINDOW_NORMAL)
1742 if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN)
1751 void CvWindow::updateImage(void* arr)
1753 myView->updateImage(arr);
1757 void CvWindow::displayInfo(QString text, int delayms)
1759 myView->startDisplayInfo(text, delayms);
1763 void CvWindow::displayStatusBar(QString text, int delayms)
1766 myStatusBar->showMessage(text, delayms);
1770 void CvWindow::enablePropertiesButton()
1772 if (!vect_QActions.empty())
1773 vect_QActions[9]->setDisabled(false);
1777 CvButtonbar* CvWindow::createButtonBar(QString name_bar)
1779 QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel, name_bar);
1780 t->setAlignment(Qt::AlignHCenter);
1782 QPointer<QBoxLayout> myLayout = global_control_panel->myLayout;
1784 myLayout->insertLayout(myLayout->count(), t);
1790 void CvWindow::addSlider(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback on_change)
1792 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change);
1793 t->setAlignment(Qt::AlignHCenter);
1795 QPointer<QBoxLayout> myLayout;
1799 myLayout = w->myBarLayout;
1803 myLayout = global_control_panel->myLayout;
1805 //if first one, enable control panel
1806 if (myLayout->count() == 0)
1807 guiMainThread->enablePropertiesButtonEachWindow();
1810 myLayout->insertLayout(myLayout->count(), t);
1814 void CvWindow::addSlider2(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata)
1816 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change, userdata);
1817 t->setAlignment(Qt::AlignHCenter);
1819 QPointer<QBoxLayout> myLayout;
1823 myLayout = w->myBarLayout;
1827 myLayout = global_control_panel->myLayout;
1829 //if first one, enable control panel
1830 if (myLayout->count() == 0)
1831 guiMainThread->enablePropertiesButtonEachWindow();
1834 myLayout->insertLayout(myLayout->count(), t);
1838 void CvWindow::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
1840 myView->setOpenGlDrawCallback(callback, userdata);
1844 void CvWindow::makeCurrentOpenGlContext()
1846 myView->makeCurrentOpenGlContext();
1850 void CvWindow::updateGl()
1856 bool CvWindow::isOpenGl()
1858 return mode_display == CV_MODE_OPENGL;
1862 void CvWindow::setViewportSize(QSize _size)
1864 myView->getWidget()->resize(_size);
1865 myView->setSize(_size);
1869 void CvWindow::createBarLayout()
1871 myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1872 myBarLayout->setObjectName(QString::fromUtf8("barLayout"));
1873 myBarLayout->setContentsMargins(0, 0, 0, 0);
1874 myBarLayout->setSpacing(0);
1875 myBarLayout->setMargin(0);
1879 void CvWindow::createGlobalLayout()
1881 myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1882 myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout"));
1883 myGlobalLayout->setContentsMargins(0, 0, 0, 0);
1884 myGlobalLayout->setSpacing(0);
1885 myGlobalLayout->setMargin(0);
1886 setMinimumSize(1, 1);
1888 if (param_flags == CV_WINDOW_AUTOSIZE)
1889 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1890 else if (param_flags == CV_WINDOW_NORMAL)
1891 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1895 void CvWindow::createView()
1897 #ifdef HAVE_QT_OPENGL
1899 myView = new OpenGlViewPort(this);
1902 myView = new DefaultViewPort(this, param_ratio_mode);
1906 void CvWindow::createActions()
1908 vect_QActions.resize(10);
1910 QWidget* view = myView->getWidget();
1912 //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually
1913 vect_QActions[0] = new QAction(QIcon(":/left-icon"), "Panning left (CTRL+arrowLEFT)", this);
1914 vect_QActions[0]->setIconVisibleInMenu(true);
1915 QObject::connect(vect_QActions[0], SIGNAL(triggered()), view, SLOT(siftWindowOnLeft()));
1917 vect_QActions[1] = new QAction(QIcon(":/right-icon"), "Panning right (CTRL+arrowRIGHT)", this);
1918 vect_QActions[1]->setIconVisibleInMenu(true);
1919 QObject::connect(vect_QActions[1], SIGNAL(triggered()), view, SLOT(siftWindowOnRight()));
1921 vect_QActions[2] = new QAction(QIcon(":/up-icon"), "Panning up (CTRL+arrowUP)", this);
1922 vect_QActions[2]->setIconVisibleInMenu(true);
1923 QObject::connect(vect_QActions[2], SIGNAL(triggered()), view, SLOT(siftWindowOnUp()));
1925 vect_QActions[3] = new QAction(QIcon(":/down-icon"), "Panning down (CTRL+arrowDOWN)", this);
1926 vect_QActions[3]->setIconVisibleInMenu(true);
1927 QObject::connect(vect_QActions[3], SIGNAL(triggered()), view, SLOT(siftWindowOnDown()) );
1929 vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"), "Zoom x1 (CTRL+P)", this);
1930 vect_QActions[4]->setIconVisibleInMenu(true);
1931 QObject::connect(vect_QActions[4], SIGNAL(triggered()), view, SLOT(resetZoom()));
1933 vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"), tr("Zoom x%1 (see label) (CTRL+X)").arg(threshold_zoom_img_region), this);
1934 vect_QActions[5]->setIconVisibleInMenu(true);
1935 QObject::connect(vect_QActions[5], SIGNAL(triggered()), view, SLOT(imgRegion()));
1937 vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"), "Zoom in (CTRL++)", this);
1938 vect_QActions[6]->setIconVisibleInMenu(true);
1939 QObject::connect(vect_QActions[6], SIGNAL(triggered()), view, SLOT(ZoomIn()));
1941 vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"), "Zoom out (CTRL+-)", this);
1942 vect_QActions[7]->setIconVisibleInMenu(true);
1943 QObject::connect(vect_QActions[7], SIGNAL(triggered()), view, SLOT(ZoomOut()));
1945 vect_QActions[8] = new QAction(QIcon(":/save-icon"), "Save current image (CTRL+S)", this);
1946 vect_QActions[8]->setIconVisibleInMenu(true);
1947 QObject::connect(vect_QActions[8], SIGNAL(triggered()), view, SLOT(saveView()));
1949 vect_QActions[9] = new QAction(QIcon(":/properties-icon"), "Display properties window (CTRL+P)", this);
1950 vect_QActions[9]->setIconVisibleInMenu(true);
1951 QObject::connect(vect_QActions[9], SIGNAL(triggered()), this, SLOT(displayPropertiesWin()));
1953 if (global_control_panel->myLayout->count() == 0)
1954 vect_QActions[9]->setDisabled(true);
1958 void CvWindow::createShortcuts()
1960 vect_QShortcuts.resize(10);
1962 QWidget* view = myView->getWidget();
1964 vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this);
1965 QObject::connect(vect_QShortcuts[0], SIGNAL(activated()), view, SLOT(siftWindowOnLeft()));
1967 vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this);
1968 QObject::connect(vect_QShortcuts[1], SIGNAL(activated()), view, SLOT(siftWindowOnRight()));
1970 vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this);
1971 QObject::connect(vect_QShortcuts[2], SIGNAL(activated()), view, SLOT(siftWindowOnUp()));
1973 vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this);
1974 QObject::connect(vect_QShortcuts[3], SIGNAL(activated()), view, SLOT(siftWindowOnDown()));
1976 vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this);
1977 QObject::connect(vect_QShortcuts[4], SIGNAL(activated()), view, SLOT(resetZoom()));
1979 vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this);
1980 QObject::connect(vect_QShortcuts[5], SIGNAL(activated()), view, SLOT(imgRegion()));
1982 vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this);
1983 QObject::connect(vect_QShortcuts[6], SIGNAL(activated()), view, SLOT(ZoomIn()));
1985 vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this);
1986 QObject::connect(vect_QShortcuts[7], SIGNAL(activated()), view, SLOT(ZoomOut()));
1988 vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this);
1989 QObject::connect(vect_QShortcuts[8], SIGNAL(activated()), view, SLOT(saveView()));
1991 vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this);
1992 QObject::connect(vect_QShortcuts[9], SIGNAL(activated()), this, SLOT(displayPropertiesWin()));
1996 void CvWindow::createToolBar()
1998 myToolBar = new QToolBar(this);
1999 myToolBar->setFloatable(false); //is not a window
2000 myToolBar->setFixedHeight(28);
2001 myToolBar->setMinimumWidth(1);
2003 foreach (QAction *a, vect_QActions)
2004 myToolBar->addAction(a);
2008 void CvWindow::createStatusBar()
2010 myStatusBar = new QStatusBar(this);
2011 myStatusBar->setSizeGripEnabled(false);
2012 myStatusBar->setFixedHeight(20);
2013 myStatusBar->setMinimumWidth(1);
2014 myStatusBar_msg = new QLabel;
2016 //I comment this because if we change the style, myview (the picture)
2017 //will not be the correct size anymore (will lost 2 pixel because of the borders)
2019 //myStatusBar_msg->setFrameStyle(QFrame::Raised);
2021 myStatusBar_msg->setAlignment(Qt::AlignHCenter);
2022 myStatusBar->addWidget(myStatusBar_msg);
2026 void CvWindow::hideTools()
2032 myStatusBar->hide();
2034 if (global_control_panel)
2035 global_control_panel->hide();
2039 void CvWindow::showTools()
2045 myStatusBar->show();
2049 CvWinProperties* CvWindow::createParameterWindow()
2051 QString name_paraWindow = QFileInfo(QApplication::applicationFilePath()).fileName() + " settings";
2053 CvWinProperties* result = new CvWinProperties(name_paraWindow, guiMainThread);
2059 void CvWindow::displayPropertiesWin()
2061 if (global_control_panel->isHidden())
2062 global_control_panel->show();
2064 global_control_panel->hide();
2068 //Need more test here !
2069 void CvWindow::keyPressEvent(QKeyEvent *evnt)
2071 //see http://doc.trolltech.com/4.6/qt.html#Key-enum
2072 int key = evnt->key();
2074 Qt::Key qtkey = static_cast<Qt::Key>(key);
2075 char asciiCode = QTest::keyToAscii(qtkey);
2077 key = static_cast<int>(asciiCode);
2079 key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend
2081 //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions
2082 if (evnt->modifiers() != Qt::ControlModifier)
2087 key_pressed.wakeAll();
2091 QWidget::keyPressEvent(evnt);
2095 void CvWindow::icvLoadControlPanel()
2097 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");
2099 int bsize = settings.beginReadArray("bars");
2101 if (bsize == global_control_panel->myLayout->layout()->count())
2103 for (int i = 0; i < bsize; ++i)
2105 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2106 settings.setArrayIndex(i);
2107 if (t->type == type_CvTrackbar)
2109 if (t->name_bar == settings.value("namebar").toString())
2111 ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt());
2114 if (t->type == type_CvButtonbar)
2116 int subsize = settings.beginReadArray(QString("buttonbar")+i);
2118 if ( subsize == ((CvButtonbar*)t)->layout()->count() )
2119 icvLoadButtonbar((CvButtonbar*)t,&settings);
2121 settings.endArray();
2126 settings.endArray();
2130 void CvWindow::icvSaveControlPanel()
2132 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel");
2134 settings.beginWriteArray("bars");
2136 for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i)
2138 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2139 settings.setArrayIndex(i);
2140 if (t->type == type_CvTrackbar)
2142 settings.setValue("namebar", QString(t->name_bar));
2143 settings.setValue("valuebar",((CvTrackbar*)t)->slider->value());
2145 if (t->type == type_CvButtonbar)
2147 settings.beginWriteArray(QString("buttonbar")+i);
2148 icvSaveButtonbar((CvButtonbar*)t,&settings);
2149 settings.endArray();
2153 settings.endArray();
2157 void CvWindow::icvSaveButtonbar(CvButtonbar* b, QSettings* settings)
2159 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2161 settings->setArrayIndex(i);
2163 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2164 QString myclass(QLatin1String(temp->metaObject()->className()));
2166 if (myclass == "CvPushButton")
2168 CvPushButton* button = (CvPushButton*) temp;
2169 settings->setValue("namebutton", button->text());
2170 settings->setValue("valuebutton", int(button->isChecked()));
2172 else if (myclass == "CvCheckBox")
2174 CvCheckBox* button = (CvCheckBox*) temp;
2175 settings->setValue("namebutton", button->text());
2176 settings->setValue("valuebutton", int(button->isChecked()));
2178 else if (myclass == "CvRadioButton")
2180 CvRadioButton* button = (CvRadioButton*) temp;
2181 settings->setValue("namebutton", button->text());
2182 settings->setValue("valuebutton", int(button->isChecked()));
2188 void CvWindow::icvLoadButtonbar(CvButtonbar* b, QSettings* settings)
2190 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2192 settings->setArrayIndex(i);
2194 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2195 QString myclass(QLatin1String(temp->metaObject()->className()));
2197 if (myclass == "CvPushButton")
2199 CvPushButton* button = (CvPushButton*) temp;
2201 if (button->text() == settings->value("namebutton").toString())
2202 button->setChecked(settings->value("valuebutton").toInt());
2204 else if (myclass == "CvCheckBox")
2206 CvCheckBox* button = (CvCheckBox*) temp;
2208 if (button->text() == settings->value("namebutton").toString())
2209 button->setChecked(settings->value("valuebutton").toInt());
2211 else if (myclass == "CvRadioButton")
2213 CvRadioButton* button = (CvRadioButton*) temp;
2215 if (button->text() == settings->value("namebutton").toString())
2216 button->setChecked(settings->value("valuebutton").toInt());
2223 void CvWindow::icvLoadTrackbars(QSettings* settings)
2225 int bsize = settings->beginReadArray("trackbars");
2227 //trackbar are saved in the same order, so no need to use icvFindTrackbarByName
2229 if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)
2231 for (int i = 0; i < bsize; ++i)
2233 settings->setArrayIndex(i);
2235 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2237 if (t->name_bar == settings->value("name").toString())
2238 t->slider->setValue(settings->value("value").toInt());
2243 settings->endArray();
2247 void CvWindow::icvSaveTrackbars(QSettings* settings)
2249 settings->beginWriteArray("trackbars");
2251 for (int i = 0; i < myBarLayout->layout()->count(); ++i)
2253 settings->setArrayIndex(i);
2255 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2257 settings->setValue("name", t->name_bar);
2258 settings->setValue("value", t->slider->value());
2261 settings->endArray();
2265 //////////////////////////////////////////////////////
2269 DefaultViewPort::DefaultViewPort(CvWindow* arg, int arg2) : QGraphicsView(arg), image2Draw_mat(0)
2271 centralWidget = arg;
2272 param_keepRatio = arg2;
2274 setContentsMargins(0, 0, 0, 0);
2275 setMinimumSize(1, 1);
2276 setAlignment(Qt::AlignHCenter);
2278 setObjectName(QString::fromUtf8("graphicsView"));
2280 timerDisplay = new QTimer(this);
2281 timerDisplay->setSingleShot(true);
2282 connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo()));
2285 positionGrabbing = QPointF(0, 0);
2286 positionCorners = QRect(0, 0, size().width(), size().height());
2290 mouseCoordinate = QPoint(-1, -1);
2293 setStyleSheet( "QGraphicsView { border-style: none; }" );
2295 image2Draw_mat = cvCreateMat(viewport()->height(), viewport()->width(), CV_8UC3);
2296 cvZero(image2Draw_mat);
2298 nbChannelOriginImage = 0;
2300 setInteractive(false);
2301 setMouseTracking(true); //receive mouse event everytime
2305 DefaultViewPort::~DefaultViewPort()
2308 cvReleaseMat(&image2Draw_mat);
2312 QWidget* DefaultViewPort::getWidget()
2318 void DefaultViewPort::setMouseCallBack(CvMouseCallback m, void* param)
2322 on_mouse_param = param;
2325 void DefaultViewPort::writeSettings(QSettings& settings)
2327 settings.setValue("matrix_view.m11", param_matrixWorld.m11());
2328 settings.setValue("matrix_view.m12", param_matrixWorld.m12());
2329 settings.setValue("matrix_view.m13", param_matrixWorld.m13());
2330 settings.setValue("matrix_view.m21", param_matrixWorld.m21());
2331 settings.setValue("matrix_view.m22", param_matrixWorld.m22());
2332 settings.setValue("matrix_view.m23", param_matrixWorld.m23());
2333 settings.setValue("matrix_view.m31", param_matrixWorld.m31());
2334 settings.setValue("matrix_view.m32", param_matrixWorld.m32());
2335 settings.setValue("matrix_view.m33", param_matrixWorld.m33());
2339 void DefaultViewPort::readSettings(QSettings& settings)
2341 qreal m11 = settings.value("matrix_view.m11", param_matrixWorld.m11()).toDouble();
2342 qreal m12 = settings.value("matrix_view.m12", param_matrixWorld.m12()).toDouble();
2343 qreal m13 = settings.value("matrix_view.m13", param_matrixWorld.m13()).toDouble();
2344 qreal m21 = settings.value("matrix_view.m21", param_matrixWorld.m21()).toDouble();
2345 qreal m22 = settings.value("matrix_view.m22", param_matrixWorld.m22()).toDouble();
2346 qreal m23 = settings.value("matrix_view.m23", param_matrixWorld.m23()).toDouble();
2347 qreal m31 = settings.value("matrix_view.m31", param_matrixWorld.m31()).toDouble();
2348 qreal m32 = settings.value("matrix_view.m32", param_matrixWorld.m32()).toDouble();
2349 qreal m33 = settings.value("matrix_view.m33", param_matrixWorld.m33()).toDouble();
2351 param_matrixWorld = QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33);
2355 double DefaultViewPort::getRatio()
2357 return param_keepRatio;
2361 void DefaultViewPort::setRatio(int flags)
2363 if (getRatio() == flags) //nothing to do
2367 if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO)
2369 centralWidget->param_ratio_mode = flags;
2370 param_keepRatio = flags;
2372 viewport()->update();
2377 void DefaultViewPort::updateImage(const CvArr* arr)
2384 if (CV_IS_IMAGE_HDR(arr))
2385 origin = ((IplImage*)arr)->origin;
2387 mat = cvGetMat(arr, &stub);
2389 if (!image2Draw_mat || !CV_ARE_SIZES_EQ(image2Draw_mat, mat))
2392 cvReleaseMat(&image2Draw_mat);
2394 //the image in ipl (to do a deep copy with cvCvtColor)
2395 image2Draw_mat = cvCreateMat(mat->rows, mat->cols, CV_8UC3);
2396 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows, image2Draw_mat->step, QImage::Format_RGB888);
2398 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2399 ratioX = width() / float(image2Draw_mat->cols);
2400 ratioY = height() / float(image2Draw_mat->rows);
2404 nbChannelOriginImage = cvGetElemType(mat);
2406 cvConvertImage(mat, image2Draw_mat, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB);
2408 viewport()->update();
2412 void DefaultViewPort::startDisplayInfo(QString text, int delayms)
2414 if (timerDisplay->isActive())
2418 if (delayms > 0) timerDisplay->start(delayms);
2423 void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
2425 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2429 void DefaultViewPort::makeCurrentOpenGlContext()
2431 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2435 void DefaultViewPort::updateGl()
2437 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2441 //Note: move 2 percent of the window
2442 void DefaultViewPort::siftWindowOnLeft()
2444 float delta = 2 * width() / (100.0 * param_matrixWorld.m11());
2445 moveView(QPointF(delta, 0));
2449 //Note: move 2 percent of the window
2450 void DefaultViewPort::siftWindowOnRight()
2452 float delta = -2 * width() / (100.0 * param_matrixWorld.m11());
2453 moveView(QPointF(delta, 0));
2457 //Note: move 2 percent of the window
2458 void DefaultViewPort::siftWindowOnUp()
2460 float delta = 2 * height() / (100.0 * param_matrixWorld.m11());
2461 moveView(QPointF(0, delta));
2465 //Note: move 2 percent of the window
2466 void DefaultViewPort::siftWindowOnDown()
2468 float delta = -2 * height() / (100.0 * param_matrixWorld.m11());
2469 moveView(QPointF(0, delta));
2473 void DefaultViewPort::imgRegion()
2475 scaleView((threshold_zoom_img_region / param_matrixWorld.m11() - 1) * 5, QPointF(size().width() / 2, size().height() / 2));
2479 void DefaultViewPort::resetZoom()
2481 param_matrixWorld.reset();
2482 controlImagePosition();
2486 void DefaultViewPort::ZoomIn()
2488 scaleView(0.5, QPointF(size().width() / 2, size().height() / 2));
2492 void DefaultViewPort::ZoomOut()
2494 scaleView(-0.5, QPointF(size().width() / 2, size().height() / 2));
2498 //can save as JPG, JPEG, BMP, PNG
2499 void DefaultViewPort::saveView()
2501 QDate date_d = QDate::currentDate();
2502 QString date_s = date_d.toString("dd.MM.yyyy");
2503 QString name_s = centralWidget->windowTitle() + "_screenshot_" + date_s;
2505 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s + ".png", tr("Images (*.png *.jpg *.bmp *.jpeg)"));
2507 if (!fileName.isEmpty()) //save the picture
2509 QString extension = fileName.right(3);
2511 // Create a new pixmap to render the viewport into
2512 QPixmap viewportPixmap(viewport()->size());
2513 viewport()->render(&viewportPixmap);
2516 if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
2518 viewportPixmap.save(fileName, "PNG");
2522 if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
2524 viewportPixmap.save(fileName, "JPG");
2528 if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
2530 viewportPixmap.save(fileName, "BMP");
2534 if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
2536 viewportPixmap.save(fileName, "JPEG");
2540 CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
2545 void DefaultViewPort::contextMenuEvent(QContextMenuEvent* evnt)
2547 if (centralWidget->vect_QActions.size() > 0)
2551 foreach (QAction *a, centralWidget->vect_QActions)
2554 menu.exec(evnt->globalPos());
2559 void DefaultViewPort::resizeEvent(QResizeEvent* evnt)
2561 controlImagePosition();
2563 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2564 ratioX = width() / float(image2Draw_mat->cols);
2565 ratioY = height() / float(image2Draw_mat->rows);
2567 if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio
2569 QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2570 newSize.scale(evnt->size(), Qt::KeepAspectRatio);
2572 //imageWidth/imageHeight = newWidth/newHeight +/- epsilon
2573 //ratioX = ratioY +/- epsilon
2574 //||ratioX - ratioY|| = epsilon
2575 if (fabs(ratioX - ratioY) * 100 > ratioX) //avoid infinity loop / epsilon = 1% of ratioX
2579 //move to the middle
2580 //newSize get the delta offset to place the picture in the middle of its parent
2581 newSize = (evnt->size() - newSize) / 2;
2583 //if the toolbar is displayed, avoid drawing myview on top of it
2584 if (centralWidget->myToolBar)
2585 if(!centralWidget->myToolBar->isHidden())
2586 newSize += QSize(0, centralWidget->myToolBar->height());
2588 move(newSize.width(), newSize.height());
2592 return QGraphicsView::resizeEvent(evnt);
2596 void DefaultViewPort::wheelEvent(QWheelEvent* evnt)
2598 scaleView(evnt->delta() / 240.0, evnt->pos());
2599 viewport()->update();
2603 void DefaultViewPort::mousePressEvent(QMouseEvent* evnt)
2605 int cv_event = -1, flags = 0;
2606 QPoint pt = evnt->pos();
2608 //icvmouseHandler: pass parameters for cv_event, flags
2609 icvmouseHandler(evnt, mouse_down, cv_event, flags);
2610 icvmouseProcessing(QPointF(pt), cv_event, flags);
2612 if (param_matrixWorld.m11()>1)
2614 setCursor(Qt::ClosedHandCursor);
2615 positionGrabbing = evnt->pos();
2618 QWidget::mousePressEvent(evnt);
2622 void DefaultViewPort::mouseReleaseEvent(QMouseEvent* evnt)
2624 int cv_event = -1, flags = 0;
2625 QPoint pt = evnt->pos();
2627 //icvmouseHandler: pass parameters for cv_event, flags
2628 icvmouseHandler(evnt, mouse_up, cv_event, flags);
2629 icvmouseProcessing(QPointF(pt), cv_event, flags);
2631 if (param_matrixWorld.m11()>1)
2632 setCursor(Qt::OpenHandCursor);
2634 QWidget::mouseReleaseEvent(evnt);
2638 void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
2640 int cv_event = -1, flags = 0;
2641 QPoint pt = evnt->pos();
2643 //icvmouseHandler: pass parameters for cv_event, flags
2644 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
2645 icvmouseProcessing(QPointF(pt), cv_event, flags);
2647 QWidget::mouseDoubleClickEvent(evnt);
2651 void DefaultViewPort::mouseMoveEvent(QMouseEvent* evnt)
2653 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
2654 QPoint pt = evnt->pos();
2656 //icvmouseHandler: pass parameters for cv_event, flags
2657 icvmouseHandler(evnt, mouse_move, cv_event, flags);
2658 icvmouseProcessing(QPointF(pt), cv_event, flags);
2660 if (param_matrixWorld.m11() > 1 && evnt->buttons() == Qt::LeftButton)
2662 QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11();
2663 positionGrabbing = evnt->pos();
2667 //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp)
2668 //the status bar will only be repaint when a click occurs.
2669 if (centralWidget->myStatusBar)
2670 viewport()->update();
2672 QWidget::mouseMoveEvent(evnt);
2676 void DefaultViewPort::paintEvent(QPaintEvent* evnt)
2678 QPainter myPainter(viewport());
2679 myPainter.setWorldTransform(param_matrixWorld);
2683 //Now disable matrixWorld for overlay display
2684 myPainter.setWorldMatrixEnabled(false);
2686 //overlay pixel values if zoomed in far enough
2687 if (param_matrixWorld.m11()*ratioX >= threshold_zoom_img_region &&
2688 param_matrixWorld.m11()*ratioY >= threshold_zoom_img_region)
2690 drawImgRegion(&myPainter);
2693 //in mode zoom/panning
2694 if (param_matrixWorld.m11() > 1)
2696 drawViewOverview(&myPainter);
2699 //for information overlay
2701 drawInstructions(&myPainter);
2704 if (centralWidget->myStatusBar)
2707 QGraphicsView::paintEvent(evnt);
2711 void DefaultViewPort::stopDisplayInfo()
2713 timerDisplay->stop();
2718 inline bool DefaultViewPort::isSameSize(IplImage* img1, IplImage* img2)
2720 return img1->width == img2->width && img1->height == img2->height;
2724 void DefaultViewPort::controlImagePosition()
2726 qreal left, top, right, bottom;
2728 //after check top-left, bottom right corner to avoid getting "out" during zoom/panning
2729 param_matrixWorld.map(0,0,&left,&top);
2733 param_matrixWorld.translate(-left,0);
2738 param_matrixWorld.translate(0,-top);
2743 QSize sizeImage = size();
2744 param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom);
2745 if (right < sizeImage.width())
2747 param_matrixWorld.translate(sizeImage.width()-right,0);
2748 right = sizeImage.width();
2750 if (bottom < sizeImage.height())
2752 param_matrixWorld.translate(0,sizeImage.height()-bottom);
2753 bottom = sizeImage.height();
2756 //save corner position
2757 positionCorners.setTopLeft(QPoint(left,top));
2758 positionCorners.setBottomRight(QPoint(right,bottom));
2759 //save also the inv matrix
2760 matrixWorld_inv = param_matrixWorld.inverted();
2762 //viewport()->update();
2765 void DefaultViewPort::moveView(QPointF delta)
2767 param_matrixWorld.translate(delta.x(),delta.y());
2768 controlImagePosition();
2769 viewport()->update();
2772 //factor is -0.5 (zoom out) or 0.5 (zoom in)
2773 void DefaultViewPort::scaleView(qreal factor,QPointF center)
2775 factor/=5;//-0.1 <-> 0.1
2776 factor+=1;//0.9 <-> 1.1
2778 //limit zoom out ---
2779 if (param_matrixWorld.m11()==1 && factor < 1)
2782 if (param_matrixWorld.m11()*factor<1)
2783 factor = 1/param_matrixWorld.m11();
2786 //limit zoom int ---
2787 if (param_matrixWorld.m11()>100 && factor > 1)
2790 //inverse the transform
2792 matrixWorld_inv.map(center.x(),center.y(),&a,&b);
2794 param_matrixWorld.translate(a-factor*a,b-factor*b);
2795 param_matrixWorld.scale(factor,factor);
2797 controlImagePosition();
2800 if (centralWidget->myStatusBar)
2801 centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000);
2803 if (param_matrixWorld.m11()>1)
2804 setCursor(Qt::OpenHandCursor);
2810 //up, down, dclick, move
2811 void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)
2813 Qt::KeyboardModifiers modifiers = evnt->modifiers();
2814 Qt::MouseButtons buttons = evnt->buttons();
2817 if(modifiers & Qt::ShiftModifier)
2818 flags |= CV_EVENT_FLAG_SHIFTKEY;
2819 if(modifiers & Qt::ControlModifier)
2820 flags |= CV_EVENT_FLAG_CTRLKEY;
2821 if(modifiers & Qt::AltModifier)
2822 flags |= CV_EVENT_FLAG_ALTKEY;
2824 if(buttons & Qt::LeftButton)
2825 flags |= CV_EVENT_FLAG_LBUTTON;
2826 if(buttons & Qt::RightButton)
2827 flags |= CV_EVENT_FLAG_RBUTTON;
2828 if(buttons & Qt::MidButton)
2829 flags |= CV_EVENT_FLAG_MBUTTON;
2831 cv_event = CV_EVENT_MOUSEMOVE;
2832 switch(evnt->button())
2834 case Qt::LeftButton:
2835 cv_event = tableMouseButtons[category][0];
2836 flags |= CV_EVENT_FLAG_LBUTTON;
2838 case Qt::RightButton:
2839 cv_event = tableMouseButtons[category][1];
2840 flags |= CV_EVENT_FLAG_RBUTTON;
2843 cv_event = tableMouseButtons[category][2];
2844 flags |= CV_EVENT_FLAG_MBUTTON;
2851 void DefaultViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
2853 //to convert mouse coordinate
2855 matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy);
2857 mouseCoordinate.rx()=floor(pfx/ratioX);
2858 mouseCoordinate.ry()=floor(pfy/ratioY);
2861 on_mouse( cv_event, mouseCoordinate.x(),
2862 mouseCoordinate.y(), flags, on_mouse_param );
2866 QSize DefaultViewPort::sizeHint() const
2869 return QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2871 return QGraphicsView::sizeHint();
2875 void DefaultViewPort::draw2D(QPainter *painter)
2877 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888);
2878 painter->drawImage(QRect(0,0,viewport()->width(),viewport()->height()), image2Draw_qt, QRect(0,0, image2Draw_qt.width(), image2Draw_qt.height()) );
2881 //only if CV_8UC1 or CV_8UC3
2882 void DefaultViewPort::drawStatusBar()
2884 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2887 if (mouseCoordinate.x()>=0 &&
2888 mouseCoordinate.y()>=0 &&
2889 mouseCoordinate.x()<image2Draw_qt.width() &&
2890 mouseCoordinate.y()<image2Draw_qt.height())
2891 // if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0)
2893 QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate);
2895 if (nbChannelOriginImage==CV_8UC3 )
2897 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2898 .arg(mouseCoordinate.x())
2899 .arg(mouseCoordinate.y())+
2900 tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+
2901 tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+
2902 tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2])
2906 if (nbChannelOriginImage==CV_8UC1)
2908 //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed
2909 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2910 .arg(mouseCoordinate.x())
2911 .arg(mouseCoordinate.y())+
2912 tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue))
2918 //accept only CV_8UC1 and CV_8UC8 image for now
2919 void DefaultViewPort::drawImgRegion(QPainter *painter)
2921 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2924 double pixel_width = param_matrixWorld.m11()*ratioX;
2925 double pixel_height = param_matrixWorld.m11()*ratioY;
2927 qreal offsetX = param_matrixWorld.dx()/pixel_width;
2928 offsetX = offsetX - floor(offsetX);
2929 qreal offsetY = param_matrixWorld.dy()/pixel_height;
2930 offsetY = offsetY - floor(offsetY);
2932 QSize view = size();
2933 QVarLengthArray<QLineF, 30> linesX;
2934 for (qreal _x = offsetX*pixel_width; _x < view.width(); _x += pixel_width )
2935 linesX.append(QLineF(_x, 0, _x, view.height()));
2937 QVarLengthArray<QLineF, 30> linesY;
2938 for (qreal _y = offsetY*pixel_height; _y < view.height(); _y += pixel_height )
2939 linesY.append(QLineF(0, _y, view.width(), _y));
2942 QFont f = painter->font();
2943 int original_font_size = f.pointSize();
2945 //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2946 f.setPixelSize(10+(pixel_height-threshold_zoom_img_region)/5);
2947 painter->setFont(f);
2950 for (int j=-1;j<height()/pixel_height;j++)//-1 because display the pixels top rows left columns
2951 for (int i=-1;i<width()/pixel_width;i++)//-1
2953 // Calculate top left of the pixel's position in the viewport (screen space)
2954 QPointF pos_in_view((i+offsetX)*pixel_width, (j+offsetY)*pixel_height);
2956 // Calculate top left of the pixel's position in the image (image space)
2957 QPointF pos_in_image = matrixWorld_inv.map(pos_in_view);// Top left of pixel in view
2958 pos_in_image.rx() = pos_in_image.x()/ratioX;
2959 pos_in_image.ry() = pos_in_image.y()/ratioY;
2960 QPoint point_in_image(pos_in_image.x() + 0.5f,pos_in_image.y() + 0.5f);// Add 0.5 for rounding
2963 if (image2Draw_qt.valid(point_in_image))
2964 rgbValue = image2Draw_qt.pixel(point_in_image);
2966 rgbValue = qRgb(0,0,0);
2968 if (nbChannelOriginImage==CV_8UC3)
2972 val = tr("%1 %2").arg(point2.x()).arg(point2.y());
2973 painter->setPen(QPen(Qt::black, 1));
2974 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
2975 Qt::AlignCenter, val);
2979 val = tr("%1").arg(qRed(rgbValue));
2980 painter->setPen(QPen(Qt::red, 1));
2981 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height/3),
2982 Qt::AlignCenter, val);
2984 val = tr("%1").arg(qGreen(rgbValue));
2985 painter->setPen(QPen(Qt::green, 1));
2986 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+pixel_height/3,pixel_width,pixel_height/3),
2987 Qt::AlignCenter, val);
2989 val = tr("%1").arg(qBlue(rgbValue));
2990 painter->setPen(QPen(Qt::blue, 1));
2991 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+2*pixel_height/3,pixel_width,pixel_height/3),
2992 Qt::AlignCenter, val);
2996 if (nbChannelOriginImage==CV_8UC1)
2998 QString val = tr("%1").arg(qRed(rgbValue));
2999 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height),
3000 Qt::AlignCenter, val);
3004 painter->setPen(QPen(Qt::black, 1));
3005 painter->drawLines(linesX.data(), linesX.size());
3006 painter->drawLines(linesY.data(), linesY.size());
3009 f.setPointSize(original_font_size);
3010 painter->setFont(f);
3014 void DefaultViewPort::drawViewOverview(QPainter *painter)
3016 QSize viewSize = size();
3017 viewSize.scale ( 100, 100,Qt::KeepAspectRatio );
3019 const int margin = 5;
3021 //draw the image's location
3022 painter->setBrush(QColor(0, 0, 0, 127));
3023 painter->setPen(Qt::darkGreen);
3024 painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height()));
3026 //daw the view's location inside the image
3027 qreal ratioSize = 1/param_matrixWorld.m11();
3028 qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height());
3029 painter->setPen(Qt::darkBlue);
3030 painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin,
3031 -positionCorners.top()*ratioSize*ratioWindow,
3032 (viewSize.width()-1)*ratioSize,
3033 (viewSize.height()-1)*ratioSize)
3037 void DefaultViewPort::drawInstructions(QPainter *painter)
3039 QFontMetrics metrics = QFontMetrics(font());
3040 int border = qMax(4, metrics.leading());
3042 QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
3043 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3044 painter->setRenderHint(QPainter::TextAntialiasing);
3045 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3046 QColor(0, 0, 0, 127));
3047 painter->setPen(Qt::white);
3048 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3049 QColor(0, 0, 0, 127));
3051 painter->drawText((width() - qrect.width())/2, border,
3052 qrect.width(), qrect.height(),
3053 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3057 void DefaultViewPort::setSize(QSize /*size_*/)
3062 //////////////////////////////////////////////////////
3065 #ifdef HAVE_QT_OPENGL
3067 OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)
3076 OpenGlViewPort::~OpenGlViewPort()
3080 QWidget* OpenGlViewPort::getWidget()
3085 void OpenGlViewPort::setMouseCallBack(CvMouseCallback callback, void* param)
3087 mouseCallback = callback;
3091 void OpenGlViewPort::writeSettings(QSettings& /*settings*/)
3095 void OpenGlViewPort::readSettings(QSettings& /*settings*/)
3099 double OpenGlViewPort::getRatio()
3101 return (double)width() / height();
3104 void OpenGlViewPort::setRatio(int /*flags*/)
3108 void OpenGlViewPort::updateImage(const CvArr* /*arr*/)
3112 void OpenGlViewPort::startDisplayInfo(QString /*text*/, int /*delayms*/)
3116 void OpenGlViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
3118 glDrawCallback = callback;
3119 glDrawData = userdata;
3122 void OpenGlViewPort::makeCurrentOpenGlContext()
3127 void OpenGlViewPort::updateGl()
3129 QGLWidget::updateGL();
3132 void OpenGlViewPort::initializeGL()
3134 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3137 void OpenGlViewPort::resizeGL(int w, int h)
3139 glViewport(0, 0, w, h);
3142 void OpenGlViewPort::paintGL()
3144 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3147 glDrawCallback(glDrawData);
3150 void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)
3152 int cv_event = -1, flags = 0;
3153 QPoint pt = evnt->pos();
3155 icvmouseHandler(evnt, mouse_down, cv_event, flags);
3156 icvmouseProcessing(QPointF(pt), cv_event, flags);
3158 QGLWidget::mousePressEvent(evnt);
3162 void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)
3164 int cv_event = -1, flags = 0;
3165 QPoint pt = evnt->pos();
3167 icvmouseHandler(evnt, mouse_up, cv_event, flags);
3168 icvmouseProcessing(QPointF(pt), cv_event, flags);
3170 QGLWidget::mouseReleaseEvent(evnt);
3174 void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
3176 int cv_event = -1, flags = 0;
3177 QPoint pt = evnt->pos();
3179 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
3180 icvmouseProcessing(QPointF(pt), cv_event, flags);
3182 QGLWidget::mouseDoubleClickEvent(evnt);
3186 void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)
3188 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
3189 QPoint pt = evnt->pos();
3191 //icvmouseHandler: pass parameters for cv_event, flags
3192 icvmouseHandler(evnt, mouse_move, cv_event, flags);
3193 icvmouseProcessing(QPointF(pt), cv_event, flags);
3195 QGLWidget::mouseMoveEvent(evnt);
3198 void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)
3200 Qt::KeyboardModifiers modifiers = evnt->modifiers();
3201 Qt::MouseButtons buttons = evnt->buttons();
3204 if (modifiers & Qt::ShiftModifier)
3205 flags |= CV_EVENT_FLAG_SHIFTKEY;
3206 if (modifiers & Qt::ControlModifier)
3207 flags |= CV_EVENT_FLAG_CTRLKEY;
3208 if (modifiers & Qt::AltModifier)
3209 flags |= CV_EVENT_FLAG_ALTKEY;
3211 if (buttons & Qt::LeftButton)
3212 flags |= CV_EVENT_FLAG_LBUTTON;
3213 if (buttons & Qt::RightButton)
3214 flags |= CV_EVENT_FLAG_RBUTTON;
3215 if (buttons & Qt::MidButton)
3216 flags |= CV_EVENT_FLAG_MBUTTON;
3218 cv_event = CV_EVENT_MOUSEMOVE;
3219 switch (evnt->button())
3221 case Qt::LeftButton:
3222 cv_event = tableMouseButtons[category][0];
3223 flags |= CV_EVENT_FLAG_LBUTTON;
3226 case Qt::RightButton:
3227 cv_event = tableMouseButtons[category][1];
3228 flags |= CV_EVENT_FLAG_RBUTTON;
3232 cv_event = tableMouseButtons[category][2];
3233 flags |= CV_EVENT_FLAG_MBUTTON;
3242 void OpenGlViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
3245 mouseCallback(cv_event, pt.x(), pt.y(), flags, mouseData);
3249 QSize OpenGlViewPort::sizeHint() const
3251 if (size.width() > 0 && size.height() > 0)
3254 return QGLWidget::sizeHint();
3257 void OpenGlViewPort::setSize(QSize size_)