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--------------------//
46 #include <window_QT.h>
63 //Static and global first
64 static GuiReceiver *guiMainThread = NULL;
65 static int parameterSystemC = 1;
66 static char* parameterSystemV[] = {(char*)""};
67 static bool multiThreads = false;
68 static int last_key = -1;
69 QWaitCondition key_pressed;
71 static const unsigned int threshold_zoom_img_region = 30;
72 //the minimum zoom value to start displaying the values in the grid
73 //that is also the number of pixel per grid
75 static CvWinProperties* global_control_panel = NULL;
76 //end static and global
79 CV_IMPL CvFont cvFontQt(const char* nameFont, int pointSize,CvScalar color,int weight,int style, int spacing)
83 //CvScalar color <- only Qt (blue_component, green_component, red\_component[, alpha_component])
84 int font_face;//<- style in Qt
90 int thickness;//<- weight in Qt
91 float dx;//spacing letter in Qt (0 default) in pixel
92 int line_type;//<- pointSize in Qt
94 CvFont f = {nameFont,color,style,NULL,NULL,NULL,0,0,0,weight,spacing,pointSize};
99 CV_IMPL void cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont* font)
102 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
104 QMetaObject::invokeMethod(guiMainThread,
107 Q_ARG(void*, (void*) img),
108 Q_ARG(QString,QString(text)),
109 Q_ARG(QPoint, QPoint(org.x,org.y)),
110 Q_ARG(void*,(void*) font));
114 double cvGetRatioWindow_QT(const char* name)
117 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
120 QMetaObject::invokeMethod(guiMainThread,
122 //Qt::DirectConnection,
124 Q_RETURN_ARG(double, result),
125 Q_ARG(QString, QString(name)));
131 void cvSetRatioWindow_QT(const char* name,double prop_value)
135 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
137 QMetaObject::invokeMethod(guiMainThread,
140 Q_ARG(QString, QString(name)),
141 Q_ARG(double, prop_value));
145 double cvGetPropWindow_QT(const char* name)
148 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
151 QMetaObject::invokeMethod(guiMainThread,
153 //Qt::DirectConnection,
155 Q_RETURN_ARG(double, result),
156 Q_ARG(QString, QString(name)));
162 void cvSetPropWindow_QT(const char* name,double prop_value)
165 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
167 QMetaObject::invokeMethod(guiMainThread,
170 Q_ARG(QString, QString(name)),
171 Q_ARG(double, prop_value));
175 void cvSetModeWindow_QT(const char* name, double prop_value)
178 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
180 QMetaObject::invokeMethod(guiMainThread,
183 Q_ARG(QString, QString(name)),
184 Q_ARG(double, prop_value));
188 double cvGetModeWindow_QT(const char* name)
191 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
195 QMetaObject::invokeMethod(guiMainThread,
198 Q_RETURN_ARG(double, result),
199 Q_ARG(QString, QString(name)));
205 CV_IMPL void cvDisplayOverlay(const char* name, const char* text, int delayms)
208 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
210 QMetaObject::invokeMethod(guiMainThread,
213 //Qt::DirectConnection,
214 Q_ARG(QString, QString(name)),
215 Q_ARG(QString, QString(text)),
216 Q_ARG(int, delayms));
220 CV_IMPL void cvSaveWindowParameters(const char* name)
223 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
225 QMetaObject::invokeMethod(guiMainThread,
226 "saveWindowParameters",
228 Q_ARG(QString, QString(name)));
232 CV_IMPL void cvLoadWindowParameters(const char* name)
235 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
237 QMetaObject::invokeMethod(guiMainThread,
238 "loadWindowParameters",
240 Q_ARG(QString, QString(name)));
244 CV_IMPL void cvDisplayStatusBar(const char* name, const char* text, int delayms)
247 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
249 QMetaObject::invokeMethod(guiMainThread,
252 //Qt::DirectConnection,
253 Q_ARG(QString, QString(name)),
254 Q_ARG(QString, QString(text)),
255 Q_ARG(int, delayms));
259 CV_IMPL int cvWaitKey(int delay)
266 unsigned long delayms = delay <= 0 ? ULONG_MAX : delay; //in milliseconds
271 if (key_pressed.wait(&mutexKey, delayms)) //false if timeout
280 //cannot use wait here because events will not be distributed before processEvents (the main eventLoop is broken)
281 //so I create a Thread for the QTimer
284 guiMainThread->timer->start(delay);
288 while (!guiMainThread->bTimeOut)
290 qApp->processEvents(QEventLoop::AllEvents);
292 if (!guiMainThread)//when all the windows are deleted
300 guiMainThread->timer->stop();
301 //printf("keypressed\n");
312 * //will not work, I broke the event loop !!!!
314 QWaitCondition waitCondition;
315 waitCondition.wait(&dummy, 2);
318 //to decrease CPU usage
319 //sleep 1 millisecond
320 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
328 guiMainThread->bTimeOut = false;
336 //This function is experimental and some functions (such as cvSet/getWindowProperty will not work)
337 //We recommend not using this function for now
338 CV_IMPL int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[])
341 QFuture<int> future = QtConcurrent::run(pt2Func, argc, argv);
342 return guiMainThread->start();
346 CV_IMPL void cvStopLoop()
352 static CvWindow* icvFindWindowByName(QString name)
354 CvWindow* window = 0;
356 //This is not a very clean way to do the stuff. Indeed, QAction automatically generate toolTil (QLabel)
357 //that can be grabbed here and crash the code at 'w->param_name==name'.
358 foreach (QWidget* widget, QApplication::topLevelWidgets())
360 if (widget->isWindow() && !widget->parentWidget())//is a window without parent
362 CvWinModel* temp = (CvWinModel*) widget;
364 if (temp->type == type_CvWindow)
366 CvWindow* w = (CvWindow*) temp;
367 if (w->windowTitle() == name)
380 static CvBar* icvFindBarByName(QBoxLayout* layout, QString name_bar, typeBar type)
385 int stop_index = layout->layout()->count();
387 for (int i = 0; i < stop_index; ++i)
389 CvBar* t = (CvBar*) layout->layout()->itemAt(i);
391 if (t->type == type && t->name_bar == name_bar)
399 static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char* name_window, QBoxLayout* layout = NULL)
401 QString nameQt(name_trackbar);
403 if (!name_window && global_control_panel) //window name is null and we have a control panel
404 layout = global_control_panel->myLayout;
408 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(name_window));
411 CV_Error(CV_StsNullPtr, "NULL window handler");
413 if (w->param_gui_mode == CV_GUI_NORMAL)
414 return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
416 if (w->param_gui_mode == CV_GUI_EXPANDED)
418 CvBar* result = icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
421 return (CvTrackbar*) result;
423 return (CvTrackbar*) icvFindBarByName(global_control_panel->myLayout, nameQt, type_CvTrackbar);
430 //layout was specified
431 return (CvTrackbar*) icvFindBarByName(layout, nameQt, type_CvTrackbar);
436 static CvButtonbar* icvFindButtonBarByName(const char* button_name, QBoxLayout* layout)
438 QString nameQt(button_name);
439 return (CvButtonbar*) icvFindBarByName(layout, nameQt, type_CvButtonbar);
443 static int icvInitSystem(int* c, char** v)
445 //"For any GUI application using Qt, there is precisely one QApplication object"
446 if (!QApplication::instance())
448 new QApplication(*c, v);
450 qDebug() << "init done";
452 #ifdef HAVE_QT_OPENGL
453 qDebug() << "opengl support available";
461 CV_IMPL int cvInitSystem(int, char**)
463 icvInitSystem(¶meterSystemC, parameterSystemV);
468 CV_IMPL int cvNamedWindow(const char* name, int flags)
471 guiMainThread = new GuiReceiver;
474 QMetaObject::invokeMethod(guiMainThread,
476 Qt::BlockingQueuedConnection,
477 Q_ARG(QString, QString(name)),
480 guiMainThread->createWindow(QString(name), flags);
482 return 1; //Dummy value
486 CV_IMPL void cvDestroyWindow(const char* name)
489 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
491 QMetaObject::invokeMethod(guiMainThread,
493 //Qt::BlockingQueuedConnection,
495 Q_ARG(QString, QString(name)));
499 CV_IMPL void cvDestroyAllWindows()
504 QMetaObject::invokeMethod(guiMainThread,
506 //Qt::BlockingQueuedConnection,
511 CV_IMPL void* cvGetWindowHandle(const char* name)
514 CV_Error( CV_StsNullPtr, "NULL name string" );
516 return (void*) icvFindWindowByName(QLatin1String(name));
520 CV_IMPL const char* cvGetWindowName(void* window_handle)
523 CV_Error( CV_StsNullPtr, "NULL window handler" );
525 return ((CvWindow*)window_handle)->windowTitle().toLatin1().data();
529 CV_IMPL void cvMoveWindow(const char* name, int x, int y)
532 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
534 QMetaObject::invokeMethod(guiMainThread,
536 //Qt::BlockingQueuedConnection,
538 Q_ARG(QString, QString(name)),
544 CV_IMPL void cvResizeWindow(const char* name, int width, int height)
547 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
549 QMetaObject::invokeMethod(guiMainThread,
551 //Qt::BlockingQueuedConnection,
553 Q_ARG(QString, QString(name)),
559 CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata)
562 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
564 QMetaObject::invokeMethod(guiMainThread,
567 Q_ARG(QString, QString(name_bar)),
568 Q_ARG(QString, QString(window_name)),
569 Q_ARG(void*, (void*)val),
571 Q_ARG(void*, (void*)on_notify),
572 Q_ARG(void*, (void*)userdata));
574 return 1; //dummy value
578 CV_IMPL int cvStartWindowThread()
584 CV_IMPL int cvCreateTrackbar(const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change)
587 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
589 QMetaObject::invokeMethod(guiMainThread,
592 Q_ARG(QString, QString(name_bar)),
593 Q_ARG(QString, QString(window_name)),
594 Q_ARG(void*, (void*)value),
596 Q_ARG(void*, (void*)on_change));
598 return 1; //dummy value
602 CV_IMPL int cvCreateButton(const char* button_name, CvButtonCallback on_change, void* userdata, int button_type, int initial_button_state)
605 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
607 if (initial_button_state < 0 || initial_button_state > 1)
610 QMetaObject::invokeMethod(guiMainThread,
613 Q_ARG(QString, QString(button_name)),
614 Q_ARG(int, button_type),
615 Q_ARG(int, initial_button_state),
616 Q_ARG(void*, (void*)on_change),
617 Q_ARG(void*, userdata));
619 return 1;//dummy value
623 CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name)
627 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
630 result = t->slider->value();
636 CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int pos)
638 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
641 t->slider->setValue(pos);
645 /* assign callback for mouse events */
646 CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param)
648 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
651 CV_Error(CV_StsNullPtr, "NULL window handler");
653 w->setMouseCallBack(on_mouse, param);
658 CV_IMPL void cvShowImage(const char* name, const CvArr* arr)
661 guiMainThread = new GuiReceiver;
663 QMetaObject::invokeMethod(guiMainThread,
665 //Qt::BlockingQueuedConnection,
666 Qt::DirectConnection,
667 Q_ARG(QString, QString(name)),
668 Q_ARG(void*, (void*)arr));
672 #ifdef HAVE_QT_OPENGL
674 CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
677 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
679 QMetaObject::invokeMethod(guiMainThread,
680 "setOpenGlDrawCallback",
682 Q_ARG(QString, QString(window_name)),
683 Q_ARG(void*, (void*)callback),
684 Q_ARG(void*, userdata));
688 CV_IMPL void cvSetOpenGlContext(const char* window_name)
691 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
693 QMetaObject::invokeMethod(guiMainThread,
696 Q_ARG(QString, QString(window_name)));
700 CV_IMPL void cvUpdateWindow(const char* window_name)
703 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
705 QMetaObject::invokeMethod(guiMainThread,
708 Q_ARG(QString, QString(window_name)));
714 double cvGetOpenGlProp_QT(const char* name)
720 QMetaObject::invokeMethod(guiMainThread,
723 Q_RETURN_ARG(double, result),
724 Q_ARG(QString, QString(name)));
731 //////////////////////////////////////////////////////
735 GuiReceiver::GuiReceiver() : bTimeOut(false), nb_windows(0)
737 doesExternalQAppExist = (QApplication::instance() != 0);
738 icvInitSystem(¶meterSystemC, parameterSystemV);
740 timer = new QTimer(this);
741 QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
742 timer->setSingleShot(true);
746 void GuiReceiver::isLastWindow()
748 if (--nb_windows <= 0)
750 delete guiMainThread;//delete global_control_panel too
751 guiMainThread = NULL;
753 if (!doesExternalQAppExist)
761 GuiReceiver::~GuiReceiver()
763 if (global_control_panel)
765 delete global_control_panel;
766 global_control_panel = NULL;
771 void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2)
776 mat = cvGetMat(arr, &stub);
778 int nbChannelOriginImage = cvGetElemType(mat);
779 if (nbChannelOriginImage != CV_8UC3) return; //for now, font works only with 8UC3
781 QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888);
783 CvFont* font = (CvFont*)arg2;
788 QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/);
789 f.setStyle((QFont::Style) font->font_face/*style*/);
790 f.setLetterSpacing(QFont::AbsoluteSpacing, font->dx/*spacing*/);
791 //cvScalar(blue_component, green_component, red_component[, alpha_component])
792 //Qt map non-transparent to 0xFF and transparent to 0
793 //OpenCV scalar is the reverse, so 255-font->color.val[3]
794 qp.setPen(QColor(font->color.val[2], font->color.val[1], font->color.val[0], 255 - font->color.val[3]));
797 qp.drawText(org, text);
802 void GuiReceiver::saveWindowParameters(QString name)
804 QPointer<CvWindow> w = icvFindWindowByName(name);
811 void GuiReceiver::loadWindowParameters(QString name)
813 QPointer<CvWindow> w = icvFindWindowByName(name);
820 double GuiReceiver::getRatioWindow(QString name)
822 QPointer<CvWindow> w = icvFindWindowByName(name);
827 return w->getRatio();
831 void GuiReceiver::setRatioWindow(QString name, double arg2)
833 QPointer<CvWindow> w = icvFindWindowByName( name.toLatin1().data() );
838 int flags = (int) arg2;
844 double GuiReceiver::getPropWindow(QString name)
846 QPointer<CvWindow> w = icvFindWindowByName(name);
851 return (double) w->getPropWindow();
855 void GuiReceiver::setPropWindow(QString name, double arg2)
857 QPointer<CvWindow> w = icvFindWindowByName(name);
862 int flags = (int) arg2;
864 w->setPropWindow(flags);
868 double GuiReceiver::isFullScreen(QString name)
870 QPointer<CvWindow> w = icvFindWindowByName(name);
875 return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL;
879 void GuiReceiver::toggleFullScreen(QString name, double arg2)
881 QPointer<CvWindow> w = icvFindWindowByName(name);
886 int flags = (int) arg2;
888 w->toggleFullScreen(flags);
892 void GuiReceiver::createWindow(QString name, int flags)
895 CV_Error(CV_StsNullPtr, "NULL session handler" );
897 // Check the name in the storage
898 if (icvFindWindowByName(name.toLatin1().data()))
904 new CvWindow(name, flags);
908 void GuiReceiver::timeOut()
914 void GuiReceiver::displayInfo(QString name, QString text, int delayms)
916 QPointer<CvWindow> w = icvFindWindowByName(name);
919 w->displayInfo(text, delayms);
923 void GuiReceiver::displayStatusBar(QString name, QString text, int delayms)
925 QPointer<CvWindow> w = icvFindWindowByName(name);
928 w->displayStatusBar(text, delayms);
932 void GuiReceiver::showImage(QString name, void* arr)
934 QPointer<CvWindow> w = icvFindWindowByName(name);
936 if (!w) //as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null
938 cvNamedWindow(name.toLatin1().data());
939 w = icvFindWindowByName(name);
943 return; // keep silence here.
949 mat = cvGetMat(arr, &stub);
952 cv::imshow(name.toStdString(), im);
964 void GuiReceiver::destroyWindow(QString name)
966 QPointer<CvWindow> w = icvFindWindowByName(name);
972 //in not-multiThreads mode, looks like the window is hidden but not deleted
973 //so I do it manually
974 //otherwise QApplication do it for me if the exec command was executed (in multiThread mode)
981 void GuiReceiver::destroyAllWindow()
984 CV_Error(CV_StsNullPtr, "NULL session handler" );
988 // WARNING: this could even close windows from an external parent app
989 //#TODO check externalQAppExists and in case it does, close windows carefully,
990 // i.e. apply the className-check from below...
991 qApp->closeAllWindows();
995 bool isWidgetDeleted = true;
996 while(isWidgetDeleted)
998 isWidgetDeleted = false;
999 QWidgetList list = QApplication::topLevelWidgets();
1000 for (int i = 0; i < list.count(); i++)
1002 QObject *obj = list.at(i);
1003 if (obj->metaObject()->className() == QString("CvWindow"))
1006 isWidgetDeleted = true;
1015 void GuiReceiver::moveWindow(QString name, int x, int y)
1017 QPointer<CvWindow> w = icvFindWindowByName(name);
1024 void GuiReceiver::resizeWindow(QString name, int width, int height)
1026 QPointer<CvWindow> w = icvFindWindowByName(name);
1031 w->setViewportSize(QSize(width, height));
1036 void GuiReceiver::enablePropertiesButtonEachWindow()
1038 //For each window, enable window property button
1039 foreach (QWidget* widget, QApplication::topLevelWidgets())
1041 if (widget->isWindow() && !widget->parentWidget()) //is a window without parent
1043 CvWinModel* temp = (CvWinModel*) widget;
1044 if (temp->type == type_CvWindow)
1046 CvWindow* w = (CvWindow*) widget;
1048 //active window properties button
1049 w->enablePropertiesButton();
1056 void GuiReceiver::addButton(QString button_name, int button_type, int initial_button_state, void* on_change, void* userdata)
1058 if (!global_control_panel)
1061 QPointer<CvButtonbar> b;
1063 if (global_control_panel->myLayout->count() == 0) //if that is the first button attach to the control panel, create a new button bar
1065 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1066 enablePropertiesButtonEachWindow();
1071 CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count() - 1);
1073 if (lastbar->type == type_CvTrackbar) //if last bar is a trackbar, create a new buttonbar, else, attach to the current bar
1074 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1076 b = (CvButtonbar*) lastbar;
1080 b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state);
1084 void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata)
1086 QBoxLayout *layout = NULL;
1087 QPointer<CvWindow> w;
1089 if (!window_name.isEmpty())
1091 w = icvFindWindowByName(window_name);
1098 if (global_control_panel)
1099 layout = global_control_panel->myLayout;
1102 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1104 if (t) //trackbar exists
1108 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1110 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1111 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1113 CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
1117 void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change)
1119 QBoxLayout *layout = NULL;
1120 QPointer<CvWindow> w;
1122 if (!window_name.isEmpty())
1124 w = icvFindWindowByName(window_name);
1131 if (global_control_panel)
1132 layout = global_control_panel->myLayout;
1135 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1137 if (t) //trackbar exists
1141 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1143 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1144 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1146 CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
1150 int GuiReceiver::start()
1152 return qApp->exec();
1156 void GuiReceiver::setOpenGlDrawCallback(QString name, void* callback, void* userdata)
1158 QPointer<CvWindow> w = icvFindWindowByName(name);
1161 w->setOpenGlDrawCallback((CvOpenGlDrawCallback) callback, userdata);
1164 void GuiReceiver::setOpenGlContext(QString name)
1166 QPointer<CvWindow> w = icvFindWindowByName(name);
1169 w->makeCurrentOpenGlContext();
1172 void GuiReceiver::updateWindow(QString name)
1174 QPointer<CvWindow> w = icvFindWindowByName(name);
1180 double GuiReceiver::isOpenGl(QString name)
1184 QPointer<CvWindow> w = icvFindWindowByName(name);
1187 result = (double) w->isOpenGl();
1193 //////////////////////////////////////////////////////
1197 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)
1200 callback2 = on_change;
1203 create(arg, name, value, _count);
1207 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)
1209 callback = on_change;
1213 create(arg, name, value, _count);
1217 void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)
1219 type = type_CvTrackbar;
1222 setObjectName(name_bar);
1225 slider = new QSlider(Qt::Horizontal);
1226 slider->setFocusPolicy(Qt::StrongFocus);
1227 slider->setMinimum(0);
1228 slider->setMaximum(_count);
1229 slider->setPageStep(5);
1230 slider->setValue(*value);
1231 slider->setTickPosition(QSlider::TicksBelow);
1234 //Change style of the Slider
1235 //slider->setStyleSheet(str_Trackbar_css);
1237 QFile qss(":/stylesheet-trackbar");
1238 if (qss.open(QFile::ReadOnly))
1240 slider->setStyleSheet(QLatin1String(qss.readAll()));
1245 //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?)
1246 //slider->setTickPosition(QSlider::TicksBelow);
1247 label = new QPushButton;
1248 label->setFlat(true);
1249 setLabel(slider->value());
1252 QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(update(int)));
1254 QObject::connect(label, SIGNAL(clicked()), this, SLOT(createDialog()));
1256 //label->setStyleSheet("QPushButton:disabled {color: black}");
1258 addWidget(label, Qt::AlignLeft);//name + value
1259 addWidget(slider, Qt::AlignCenter);//slider
1263 void CvTrackbar::createDialog()
1267 //crash if I access the values directly and give them to QInputDialog, so do a copy first.
1268 int value = slider->value();
1269 int step = slider->singleStep();
1270 int min = slider->minimum();
1271 int max = slider->maximum();
1274 #if QT_VERSION >= 0x040500
1275 QInputDialog::getInt
1277 QInputDialog::getInteger
1279 (this->parentWidget(),
1280 tr("Slider %1").arg(name_bar),
1289 slider->setValue(i);
1293 void CvTrackbar::update(int myvalue)
1297 *dataSlider = myvalue;
1306 callback2(myvalue, userdata);
1312 void CvTrackbar::setLabel(int myvalue)
1314 QString nameNormalized = name_bar.leftJustified( 10, ' ', true );
1315 QString valueMaximum = QString("%1").arg(slider->maximum());
1316 QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum);
1317 label->setText(str);
1321 //////////////////////////////////////////////////////
1325 //here CvButtonbar class
1326 CvButtonbar::CvButtonbar(QWidget* arg, QString arg2)
1328 type = type_CvButtonbar;
1331 setObjectName(name_bar);
1333 group_button = new QButtonGroup(this);
1337 void CvButtonbar::setLabel()
1339 QString nameNormalized = name_bar.leftJustified(10, ' ', true);
1340 label->setText(nameNormalized);
1344 void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state)
1346 QString button_name = name;
1348 if (button_name == "")
1349 button_name = tr("button %1").arg(this->count());
1351 QPointer<QAbstractButton> button;
1353 if (button_type == CV_PUSH_BUTTON)
1354 button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata);
1356 if (button_type == CV_CHECKBOX)
1357 button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state);
1359 if (button_type == CV_RADIOBOX)
1361 button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state);
1362 group_button->addButton(button);
1367 if (button_type == CV_PUSH_BUTTON)
1368 QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool)));
1370 QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool)));
1372 addWidget(button, Qt::AlignCenter);
1377 //////////////////////////////////////////////////////
1382 CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4)
1389 setObjectName(button_name);
1390 setText(button_name);
1397 void CvPushButton::callCallBack(bool checked)
1400 callback(checked, userdata);
1404 CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1411 setObjectName(button_name);
1412 setCheckState((initial_button_state == 1 ? Qt::Checked : Qt::Unchecked));
1413 setText(button_name);
1420 void CvCheckBox::callCallBack(bool checked)
1423 callback(checked, userdata);
1427 CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1434 setObjectName(button_name);
1435 setChecked(initial_button_state);
1436 setText(button_name);
1442 void CvRadioButton::callCallBack(bool checked)
1445 callback(checked, userdata);
1449 //////////////////////////////////////////////////////
1453 //here CvWinProperties class
1454 CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)
1456 //setParent(parent);
1457 type = type_CvWinProperties;
1458 setWindowFlags(Qt::Tool);
1459 setContentsMargins(0, 0, 0, 0);
1460 setWindowTitle(name_paraWindow);
1461 setObjectName(name_paraWindow);
1464 myLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1465 myLayout->setObjectName(QString::fromUtf8("boxLayout"));
1466 myLayout->setContentsMargins(0, 0, 0, 0);
1467 myLayout->setSpacing(0);
1468 myLayout->setMargin(0);
1469 myLayout->setSizeConstraint(QLayout::SetFixedSize);
1470 setLayout(myLayout);
1476 void CvWinProperties::closeEvent(QCloseEvent* e)
1478 e->accept(); //intersept the close event (not sure I really need it)
1479 //an hide event is also sent. I will intercept it and do some processing
1483 void CvWinProperties::showEvent(QShowEvent* evnt)
1485 //why -1,-1 ?: do this trick because the first time the code is run,
1486 //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).
1487 //then hide will save the last position and thus, we want to retreive it (event accepted).
1488 QPoint mypos(-1, -1);
1489 QSettings settings("OpenCV2", windowTitle());
1490 mypos = settings.value("pos", mypos).toPoint();
1504 void CvWinProperties::hideEvent(QHideEvent* evnt)
1506 QSettings settings("OpenCV2", windowTitle());
1507 settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)
1512 CvWinProperties::~CvWinProperties()
1514 //clear the setting pos
1515 QSettings settings("OpenCV2", windowTitle());
1516 settings.remove("pos");
1520 //////////////////////////////////////////////////////
1524 CvWindow::CvWindow(QString name, int arg2)
1526 type = type_CvWindow;
1527 moveToThread(qApp->instance()->thread());
1529 param_flags = arg2 & 0x0000000F;
1530 param_gui_mode = arg2 & 0x000000F0;
1531 param_ratio_mode = arg2 & 0x00000F00;
1533 //setAttribute(Qt::WA_DeleteOnClose); //in other case, does not release memory
1534 setContentsMargins(0, 0, 0, 0);
1535 setWindowTitle(name);
1536 setObjectName(name);
1538 setFocus( Qt::PopupFocusReason ); //#1695 arrow keys are not recieved without the explicit focus
1541 setMinimumSize(1, 1);
1543 //1: create control panel
1544 if (!global_control_panel)
1545 global_control_panel = createParameterWindow();
1549 createGlobalLayout();
1552 #ifndef HAVE_QT_OPENGL
1553 if (arg2 & CV_WINDOW_OPENGL)
1554 CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
1555 mode_display = CV_MODE_NORMAL;
1557 mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
1558 if (mode_display == CV_MODE_OPENGL)
1559 param_gui_mode = CV_GUI_NORMAL;
1563 //4: shortcuts and actions
1564 //5: toolBar and statusbar
1565 if (param_gui_mode == CV_GUI_EXPANDED)
1574 //Now attach everything
1576 myGlobalLayout->addWidget(myToolBar, Qt::AlignCenter);
1578 myGlobalLayout->addWidget(myView->getWidget(), Qt::AlignCenter);
1580 myGlobalLayout->addLayout(myBarLayout, Qt::AlignCenter);
1583 myGlobalLayout->addWidget(myStatusBar, Qt::AlignCenter);
1585 setLayout(myGlobalLayout);
1590 CvWindow::~CvWindow()
1593 guiMainThread->isLastWindow();
1597 void CvWindow::setMouseCallBack(CvMouseCallback callback, void* param)
1599 myView->setMouseCallBack(callback, param);
1603 void CvWindow::writeSettings()
1605 //organisation and application's name
1606 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1608 settings.setValue("pos", pos());
1609 settings.setValue("size", size());
1610 settings.setValue("mode_resize" ,param_flags);
1611 settings.setValue("mode_gui", param_gui_mode);
1613 myView->writeSettings(settings);
1615 icvSaveTrackbars(&settings);
1617 if (global_control_panel)
1619 icvSaveControlPanel();
1620 settings.setValue("posPanel", global_control_panel->pos());
1626 //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars)
1627 void CvWindow::readSettings()
1629 //organisation and application's name
1630 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1632 QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();
1633 QSize _size = settings.value("size", QSize(400, 400)).toSize();
1635 param_flags = settings.value("mode_resize", param_flags).toInt();
1636 param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();
1638 param_flags = settings.value("mode_resize", param_flags).toInt();
1640 myView->readSettings(settings);
1643 icvLoadTrackbars(&settings);
1648 if (global_control_panel)
1650 icvLoadControlPanel();
1651 global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint());
1656 double CvWindow::getRatio()
1658 return myView->getRatio();
1662 void CvWindow::setRatio(int flags)
1664 myView->setRatio(flags);
1668 int CvWindow::getPropWindow()
1674 void CvWindow::setPropWindow(int flags)
1676 if (param_flags == flags) //nothing to do
1681 case CV_WINDOW_NORMAL:
1682 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1683 param_flags = flags;
1687 case CV_WINDOW_AUTOSIZE:
1688 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1689 param_flags = flags;
1699 void CvWindow::toggleFullScreen(int flags)
1701 if (isFullScreen() && flags == CV_WINDOW_NORMAL)
1708 if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN)
1717 void CvWindow::updateImage(void* arr)
1719 myView->updateImage(arr);
1723 void CvWindow::displayInfo(QString text, int delayms)
1725 myView->startDisplayInfo(text, delayms);
1729 void CvWindow::displayStatusBar(QString text, int delayms)
1732 myStatusBar->showMessage(text, delayms);
1736 void CvWindow::enablePropertiesButton()
1738 vect_QActions[9]->setDisabled(false);
1742 CvButtonbar* CvWindow::createButtonBar(QString name_bar)
1744 QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel, name_bar);
1745 t->setAlignment(Qt::AlignHCenter);
1747 QPointer<QBoxLayout> myLayout = global_control_panel->myLayout;
1749 myLayout->insertLayout(myLayout->count(), t);
1755 void CvWindow::addSlider(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback on_change)
1757 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change);
1758 t->setAlignment(Qt::AlignHCenter);
1760 QPointer<QBoxLayout> myLayout;
1764 myLayout = w->myBarLayout;
1768 myLayout = global_control_panel->myLayout;
1770 //if first one, enable control panel
1771 if (myLayout->count() == 0)
1772 guiMainThread->enablePropertiesButtonEachWindow();
1775 myLayout->insertLayout(myLayout->count(), t);
1779 void CvWindow::addSlider2(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata)
1781 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change, userdata);
1782 t->setAlignment(Qt::AlignHCenter);
1784 QPointer<QBoxLayout> myLayout;
1788 myLayout = w->myBarLayout;
1792 myLayout = global_control_panel->myLayout;
1794 //if first one, enable control panel
1795 if (myLayout->count() == 0)
1796 guiMainThread->enablePropertiesButtonEachWindow();
1799 myLayout->insertLayout(myLayout->count(), t);
1803 void CvWindow::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
1805 myView->setOpenGlDrawCallback(callback, userdata);
1809 void CvWindow::makeCurrentOpenGlContext()
1811 myView->makeCurrentOpenGlContext();
1815 void CvWindow::updateGl()
1821 bool CvWindow::isOpenGl()
1823 return mode_display == CV_MODE_OPENGL;
1827 void CvWindow::setViewportSize(QSize _size)
1829 myView->getWidget()->resize(_size);
1830 myView->setSize(_size);
1834 void CvWindow::createBarLayout()
1836 myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1837 myBarLayout->setObjectName(QString::fromUtf8("barLayout"));
1838 myBarLayout->setContentsMargins(0, 0, 0, 0);
1839 myBarLayout->setSpacing(0);
1840 myBarLayout->setMargin(0);
1844 void CvWindow::createGlobalLayout()
1846 myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1847 myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout"));
1848 myGlobalLayout->setContentsMargins(0, 0, 0, 0);
1849 myGlobalLayout->setSpacing(0);
1850 myGlobalLayout->setMargin(0);
1851 setMinimumSize(1, 1);
1853 if (param_flags == CV_WINDOW_AUTOSIZE)
1854 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1855 else if (param_flags == CV_WINDOW_NORMAL)
1856 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1860 void CvWindow::createView()
1862 #ifdef HAVE_QT_OPENGL
1864 myView = new OpenGlViewPort(this);
1867 myView = new DefaultViewPort(this, param_ratio_mode);
1871 void CvWindow::createActions()
1873 vect_QActions.resize(10);
1875 QWidget* view = myView->getWidget();
1877 //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually
1878 vect_QActions[0] = new QAction(QIcon(":/left-icon"), "Panning left (CTRL+arrowLEFT)", this);
1879 vect_QActions[0]->setIconVisibleInMenu(true);
1880 QObject::connect(vect_QActions[0], SIGNAL(triggered()), view, SLOT(siftWindowOnLeft()));
1882 vect_QActions[1] = new QAction(QIcon(":/right-icon"), "Panning right (CTRL+arrowRIGHT)", this);
1883 vect_QActions[1]->setIconVisibleInMenu(true);
1884 QObject::connect(vect_QActions[1], SIGNAL(triggered()), view, SLOT(siftWindowOnRight()));
1886 vect_QActions[2] = new QAction(QIcon(":/up-icon"), "Panning up (CTRL+arrowUP)", this);
1887 vect_QActions[2]->setIconVisibleInMenu(true);
1888 QObject::connect(vect_QActions[2], SIGNAL(triggered()), view, SLOT(siftWindowOnUp()));
1890 vect_QActions[3] = new QAction(QIcon(":/down-icon"), "Panning down (CTRL+arrowDOWN)", this);
1891 vect_QActions[3]->setIconVisibleInMenu(true);
1892 QObject::connect(vect_QActions[3], SIGNAL(triggered()), view, SLOT(siftWindowOnDown()) );
1894 vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"), "Zoom x1 (CTRL+P)", this);
1895 vect_QActions[4]->setIconVisibleInMenu(true);
1896 QObject::connect(vect_QActions[4], SIGNAL(triggered()), view, SLOT(resetZoom()));
1898 vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"), tr("Zoom x%1 (see label) (CTRL+X)").arg(threshold_zoom_img_region), this);
1899 vect_QActions[5]->setIconVisibleInMenu(true);
1900 QObject::connect(vect_QActions[5], SIGNAL(triggered()), view, SLOT(imgRegion()));
1902 vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"), "Zoom in (CTRL++)", this);
1903 vect_QActions[6]->setIconVisibleInMenu(true);
1904 QObject::connect(vect_QActions[6], SIGNAL(triggered()), view, SLOT(ZoomIn()));
1906 vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"), "Zoom out (CTRL+-)", this);
1907 vect_QActions[7]->setIconVisibleInMenu(true);
1908 QObject::connect(vect_QActions[7], SIGNAL(triggered()), view, SLOT(ZoomOut()));
1910 vect_QActions[8] = new QAction(QIcon(":/save-icon"), "Save current image (CTRL+S)", this);
1911 vect_QActions[8]->setIconVisibleInMenu(true);
1912 QObject::connect(vect_QActions[8], SIGNAL(triggered()), view, SLOT(saveView()));
1914 vect_QActions[9] = new QAction(QIcon(":/properties-icon"), "Display properties window (CTRL+P)", this);
1915 vect_QActions[9]->setIconVisibleInMenu(true);
1916 QObject::connect(vect_QActions[9], SIGNAL(triggered()), this, SLOT(displayPropertiesWin()));
1918 if (global_control_panel->myLayout->count() == 0)
1919 vect_QActions[9]->setDisabled(true);
1923 void CvWindow::createShortcuts()
1925 vect_QShortcuts.resize(10);
1927 QWidget* view = myView->getWidget();
1929 vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this);
1930 QObject::connect(vect_QShortcuts[0], SIGNAL(activated()), view, SLOT(siftWindowOnLeft()));
1932 vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this);
1933 QObject::connect(vect_QShortcuts[1], SIGNAL(activated()), view, SLOT(siftWindowOnRight()));
1935 vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this);
1936 QObject::connect(vect_QShortcuts[2], SIGNAL(activated()), view, SLOT(siftWindowOnUp()));
1938 vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this);
1939 QObject::connect(vect_QShortcuts[3], SIGNAL(activated()), view, SLOT(siftWindowOnDown()));
1941 vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this);
1942 QObject::connect(vect_QShortcuts[4], SIGNAL(activated()), view, SLOT(resetZoom()));
1944 vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this);
1945 QObject::connect(vect_QShortcuts[5], SIGNAL(activated()), view, SLOT(imgRegion()));
1947 vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this);
1948 QObject::connect(vect_QShortcuts[6], SIGNAL(activated()), view, SLOT(ZoomIn()));
1950 vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this);
1951 QObject::connect(vect_QShortcuts[7], SIGNAL(activated()), view, SLOT(ZoomOut()));
1953 vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this);
1954 QObject::connect(vect_QShortcuts[8], SIGNAL(activated()), view, SLOT(saveView()));
1956 vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this);
1957 QObject::connect(vect_QShortcuts[9], SIGNAL(activated()), this, SLOT(displayPropertiesWin()));
1961 void CvWindow::createToolBar()
1963 myToolBar = new QToolBar(this);
1964 myToolBar->setFloatable(false); //is not a window
1965 myToolBar->setFixedHeight(28);
1966 myToolBar->setMinimumWidth(1);
1968 foreach (QAction *a, vect_QActions)
1969 myToolBar->addAction(a);
1973 void CvWindow::createStatusBar()
1975 myStatusBar = new QStatusBar(this);
1976 myStatusBar->setSizeGripEnabled(false);
1977 myStatusBar->setFixedHeight(20);
1978 myStatusBar->setMinimumWidth(1);
1979 myStatusBar_msg = new QLabel;
1981 //I comment this because if we change the style, myview (the picture)
1982 //will not be the correct size anymore (will lost 2 pixel because of the borders)
1984 //myStatusBar_msg->setFrameStyle(QFrame::Raised);
1986 myStatusBar_msg->setAlignment(Qt::AlignHCenter);
1987 myStatusBar->addWidget(myStatusBar_msg);
1991 void CvWindow::hideTools()
1997 myStatusBar->hide();
1999 if (global_control_panel)
2000 global_control_panel->hide();
2004 void CvWindow::showTools()
2010 myStatusBar->show();
2014 CvWinProperties* CvWindow::createParameterWindow()
2016 QString name_paraWindow = QFileInfo(QApplication::applicationFilePath()).fileName() + " settings";
2018 CvWinProperties* result = new CvWinProperties(name_paraWindow, guiMainThread);
2024 void CvWindow::displayPropertiesWin()
2026 if (global_control_panel->isHidden())
2027 global_control_panel->show();
2029 global_control_panel->hide();
2033 //Need more test here !
2034 void CvWindow::keyPressEvent(QKeyEvent *evnt)
2036 //see http://doc.trolltech.com/4.6/qt.html#Key-enum
2037 int key = evnt->key();
2039 Qt::Key qtkey = static_cast<Qt::Key>(key);
2040 char asciiCode = QTest::keyToAscii(qtkey);
2042 key = static_cast<int>(asciiCode);
2044 key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend
2046 //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions
2047 if (evnt->modifiers() != Qt::ControlModifier)
2052 key_pressed.wakeAll();
2056 QWidget::keyPressEvent(evnt);
2060 void CvWindow::icvLoadControlPanel()
2062 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");
2064 int bsize = settings.beginReadArray("bars");
2066 if (bsize == global_control_panel->myLayout->layout()->count())
2068 for (int i = 0; i < bsize; ++i)
2070 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2071 settings.setArrayIndex(i);
2072 if (t->type == type_CvTrackbar)
2074 if (t->name_bar == settings.value("namebar").toString())
2076 ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt());
2079 if (t->type == type_CvButtonbar)
2081 int subsize = settings.beginReadArray(QString("buttonbar")+i);
2083 if ( subsize == ((CvButtonbar*)t)->layout()->count() )
2084 icvLoadButtonbar((CvButtonbar*)t,&settings);
2086 settings.endArray();
2091 settings.endArray();
2095 void CvWindow::icvSaveControlPanel()
2097 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel");
2099 settings.beginWriteArray("bars");
2101 for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i)
2103 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2104 settings.setArrayIndex(i);
2105 if (t->type == type_CvTrackbar)
2107 settings.setValue("namebar", QString(t->name_bar));
2108 settings.setValue("valuebar",((CvTrackbar*)t)->slider->value());
2110 if (t->type == type_CvButtonbar)
2112 settings.beginWriteArray(QString("buttonbar")+i);
2113 icvSaveButtonbar((CvButtonbar*)t,&settings);
2114 settings.endArray();
2118 settings.endArray();
2122 void CvWindow::icvSaveButtonbar(CvButtonbar* b, QSettings* settings)
2124 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2126 settings->setArrayIndex(i);
2128 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2129 QString myclass(QLatin1String(temp->metaObject()->className()));
2131 if (myclass == "CvPushButton")
2133 CvPushButton* button = (CvPushButton*) temp;
2134 settings->setValue("namebutton", button->text());
2135 settings->setValue("valuebutton", int(button->isChecked()));
2137 else if (myclass == "CvCheckBox")
2139 CvCheckBox* button = (CvCheckBox*) temp;
2140 settings->setValue("namebutton", button->text());
2141 settings->setValue("valuebutton", int(button->isChecked()));
2143 else if (myclass == "CvRadioButton")
2145 CvRadioButton* button = (CvRadioButton*) temp;
2146 settings->setValue("namebutton", button->text());
2147 settings->setValue("valuebutton", int(button->isChecked()));
2153 void CvWindow::icvLoadButtonbar(CvButtonbar* b, QSettings* settings)
2155 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2157 settings->setArrayIndex(i);
2159 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2160 QString myclass(QLatin1String(temp->metaObject()->className()));
2162 if (myclass == "CvPushButton")
2164 CvPushButton* button = (CvPushButton*) temp;
2166 if (button->text() == settings->value("namebutton").toString())
2167 button->setChecked(settings->value("valuebutton").toInt());
2169 else if (myclass == "CvCheckBox")
2171 CvCheckBox* button = (CvCheckBox*) temp;
2173 if (button->text() == settings->value("namebutton").toString())
2174 button->setChecked(settings->value("valuebutton").toInt());
2176 else if (myclass == "CvRadioButton")
2178 CvRadioButton* button = (CvRadioButton*) temp;
2180 if (button->text() == settings->value("namebutton").toString())
2181 button->setChecked(settings->value("valuebutton").toInt());
2188 void CvWindow::icvLoadTrackbars(QSettings* settings)
2190 int bsize = settings->beginReadArray("trackbars");
2192 //trackbar are saved in the same order, so no need to use icvFindTrackbarByName
2194 if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)
2196 for (int i = 0; i < bsize; ++i)
2198 settings->setArrayIndex(i);
2200 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2202 if (t->name_bar == settings->value("name").toString())
2203 t->slider->setValue(settings->value("value").toInt());
2208 settings->endArray();
2212 void CvWindow::icvSaveTrackbars(QSettings* settings)
2214 settings->beginWriteArray("trackbars");
2216 for (int i = 0; i < myBarLayout->layout()->count(); ++i)
2218 settings->setArrayIndex(i);
2220 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2222 settings->setValue("name", t->name_bar);
2223 settings->setValue("value", t->slider->value());
2226 settings->endArray();
2230 //////////////////////////////////////////////////////
2234 DefaultViewPort::DefaultViewPort(CvWindow* arg, int arg2) : QGraphicsView(arg), image2Draw_mat(0)
2236 centralWidget = arg;
2237 param_keepRatio = arg2;
2239 setContentsMargins(0, 0, 0, 0);
2240 setMinimumSize(1, 1);
2241 setAlignment(Qt::AlignHCenter);
2243 setObjectName(QString::fromUtf8("graphicsView"));
2245 timerDisplay = new QTimer(this);
2246 timerDisplay->setSingleShot(true);
2247 connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo()));
2250 positionGrabbing = QPointF(0, 0);
2251 positionCorners = QRect(0, 0, size().width(), size().height());
2255 mouseCoordinate = QPoint(-1, -1);
2258 setStyleSheet( "QGraphicsView { border-style: none; }" );
2260 image2Draw_mat = cvCreateMat(viewport()->height(), viewport()->width(), CV_8UC3);
2261 cvZero(image2Draw_mat);
2263 nbChannelOriginImage = 0;
2265 setInteractive(false);
2266 setMouseTracking(true); //receive mouse event everytime
2270 DefaultViewPort::~DefaultViewPort()
2273 cvReleaseMat(&image2Draw_mat);
2277 QWidget* DefaultViewPort::getWidget()
2283 void DefaultViewPort::setMouseCallBack(CvMouseCallback m, void* param)
2287 on_mouse_param = param;
2290 void DefaultViewPort::writeSettings(QSettings& settings)
2292 settings.setValue("matrix_view.m11", param_matrixWorld.m11());
2293 settings.setValue("matrix_view.m12", param_matrixWorld.m12());
2294 settings.setValue("matrix_view.m13", param_matrixWorld.m13());
2295 settings.setValue("matrix_view.m21", param_matrixWorld.m21());
2296 settings.setValue("matrix_view.m22", param_matrixWorld.m22());
2297 settings.setValue("matrix_view.m23", param_matrixWorld.m23());
2298 settings.setValue("matrix_view.m31", param_matrixWorld.m31());
2299 settings.setValue("matrix_view.m32", param_matrixWorld.m32());
2300 settings.setValue("matrix_view.m33", param_matrixWorld.m33());
2304 void DefaultViewPort::readSettings(QSettings& settings)
2306 qreal m11 = settings.value("matrix_view.m11", param_matrixWorld.m11()).toDouble();
2307 qreal m12 = settings.value("matrix_view.m12", param_matrixWorld.m12()).toDouble();
2308 qreal m13 = settings.value("matrix_view.m13", param_matrixWorld.m13()).toDouble();
2309 qreal m21 = settings.value("matrix_view.m21", param_matrixWorld.m21()).toDouble();
2310 qreal m22 = settings.value("matrix_view.m22", param_matrixWorld.m22()).toDouble();
2311 qreal m23 = settings.value("matrix_view.m23", param_matrixWorld.m23()).toDouble();
2312 qreal m31 = settings.value("matrix_view.m31", param_matrixWorld.m31()).toDouble();
2313 qreal m32 = settings.value("matrix_view.m32", param_matrixWorld.m32()).toDouble();
2314 qreal m33 = settings.value("matrix_view.m33", param_matrixWorld.m33()).toDouble();
2316 param_matrixWorld = QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33);
2320 double DefaultViewPort::getRatio()
2322 return param_keepRatio;
2326 void DefaultViewPort::setRatio(int flags)
2328 if (getRatio() == flags) //nothing to do
2332 if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO)
2334 centralWidget->param_ratio_mode = flags;
2335 param_keepRatio = flags;
2337 viewport()->update();
2342 void DefaultViewPort::updateImage(const CvArr* arr)
2349 if (CV_IS_IMAGE_HDR(arr))
2350 origin = ((IplImage*)arr)->origin;
2352 mat = cvGetMat(arr, &stub);
2354 if (!image2Draw_mat || !CV_ARE_SIZES_EQ(image2Draw_mat, mat))
2357 cvReleaseMat(&image2Draw_mat);
2359 //the image in ipl (to do a deep copy with cvCvtColor)
2360 image2Draw_mat = cvCreateMat(mat->rows, mat->cols, CV_8UC3);
2361 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows, image2Draw_mat->step, QImage::Format_RGB888);
2363 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2364 ratioX = width() / float(image2Draw_mat->cols);
2365 ratioY = height() / float(image2Draw_mat->rows);
2370 nbChannelOriginImage = cvGetElemType(mat);
2372 cvConvertImage(mat, image2Draw_mat, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB);
2374 viewport()->update();
2378 void DefaultViewPort::startDisplayInfo(QString text, int delayms)
2380 if (timerDisplay->isActive())
2384 if (delayms > 0) timerDisplay->start(delayms);
2389 void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
2391 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2395 void DefaultViewPort::makeCurrentOpenGlContext()
2397 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2401 void DefaultViewPort::updateGl()
2403 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2407 //Note: move 2 percent of the window
2408 void DefaultViewPort::siftWindowOnLeft()
2410 float delta = 2 * width() / (100.0 * param_matrixWorld.m11());
2411 moveView(QPointF(delta, 0));
2415 //Note: move 2 percent of the window
2416 void DefaultViewPort::siftWindowOnRight()
2418 float delta = -2 * width() / (100.0 * param_matrixWorld.m11());
2419 moveView(QPointF(delta, 0));
2423 //Note: move 2 percent of the window
2424 void DefaultViewPort::siftWindowOnUp()
2426 float delta = 2 * height() / (100.0 * param_matrixWorld.m11());
2427 moveView(QPointF(0, delta));
2431 //Note: move 2 percent of the window
2432 void DefaultViewPort::siftWindowOnDown()
2434 float delta = -2 * height() / (100.0 * param_matrixWorld.m11());
2435 moveView(QPointF(0, delta));
2439 void DefaultViewPort::imgRegion()
2441 scaleView((threshold_zoom_img_region / param_matrixWorld.m11() - 1) * 5, QPointF(size().width() / 2, size().height() / 2));
2445 void DefaultViewPort::resetZoom()
2447 param_matrixWorld.reset();
2448 controlImagePosition();
2452 void DefaultViewPort::ZoomIn()
2454 scaleView(0.5, QPointF(size().width() / 2, size().height() / 2));
2458 void DefaultViewPort::ZoomOut()
2460 scaleView(-0.5, QPointF(size().width() / 2, size().height() / 2));
2464 //can save as JPG, JPEG, BMP, PNG
2465 void DefaultViewPort::saveView()
2467 QDate date_d = QDate::currentDate();
2468 QString date_s = date_d.toString("dd.MM.yyyy");
2469 QString name_s = centralWidget->windowTitle() + "_screenshot_" + date_s;
2471 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s + ".png", tr("Images (*.png *.jpg *.bmp *.jpeg)"));
2473 if (!fileName.isEmpty()) //save the picture
2475 QString extension = fileName.right(3);
2477 // (no need anymore) create the image resized to receive the 'screenshot'
2478 // image2Draw_qt_resized = QImage(viewport()->width(), viewport()->height(),QImage::Format_RGB888);
2480 QPainter saveimage(&image2Draw_qt_resized);
2481 this->render(&saveimage);
2484 if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
2486 image2Draw_qt_resized.save(fileName, "PNG");
2490 if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
2492 image2Draw_qt_resized.save(fileName, "JPG");
2496 if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
2498 image2Draw_qt_resized.save(fileName, "BMP");
2502 if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
2504 image2Draw_qt_resized.save(fileName, "JPEG");
2508 CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
2513 void DefaultViewPort::contextMenuEvent(QContextMenuEvent* evnt)
2515 if (centralWidget->vect_QActions.size() > 0)
2519 foreach (QAction *a, centralWidget->vect_QActions)
2522 menu.exec(evnt->globalPos());
2527 void DefaultViewPort::resizeEvent(QResizeEvent* evnt)
2529 controlImagePosition();
2531 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2532 ratioX = width() / float(image2Draw_mat->cols);
2533 ratioY = height() / float(image2Draw_mat->rows);
2535 if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio
2537 QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2538 newSize.scale(evnt->size(), Qt::KeepAspectRatio);
2540 //imageWidth/imageHeight = newWidth/newHeight +/- epsilon
2541 //ratioX = ratioY +/- epsilon
2542 //||ratioX - ratioY|| = epsilon
2543 if (fabs(ratioX - ratioY) * 100 > ratioX) //avoid infinity loop / epsilon = 1% of ratioX
2547 //move to the middle
2548 //newSize get the delta offset to place the picture in the middle of its parent
2549 newSize = (evnt->size() - newSize) / 2;
2551 //if the toolbar is displayed, avoid drawing myview on top of it
2552 if (centralWidget->myToolBar)
2553 if(!centralWidget->myToolBar->isHidden())
2554 newSize += QSize(0, centralWidget->myToolBar->height());
2556 move(newSize.width(), newSize.height());
2560 return QGraphicsView::resizeEvent(evnt);
2564 void DefaultViewPort::wheelEvent(QWheelEvent* evnt)
2566 scaleView(evnt->delta() / 240.0, evnt->pos());
2567 viewport()->update();
2571 void DefaultViewPort::mousePressEvent(QMouseEvent* evnt)
2573 int cv_event = -1, flags = 0;
2574 QPoint pt = evnt->pos();
2576 //icvmouseHandler: pass parameters for cv_event, flags
2577 icvmouseHandler(evnt, mouse_down, cv_event, flags);
2578 icvmouseProcessing(QPointF(pt), cv_event, flags);
2580 if (param_matrixWorld.m11()>1)
2582 setCursor(Qt::ClosedHandCursor);
2583 positionGrabbing = evnt->pos();
2586 QWidget::mousePressEvent(evnt);
2590 void DefaultViewPort::mouseReleaseEvent(QMouseEvent* evnt)
2592 int cv_event = -1, flags = 0;
2593 QPoint pt = evnt->pos();
2595 //icvmouseHandler: pass parameters for cv_event, flags
2596 icvmouseHandler(evnt, mouse_up, cv_event, flags);
2597 icvmouseProcessing(QPointF(pt), cv_event, flags);
2599 if (param_matrixWorld.m11()>1)
2600 setCursor(Qt::OpenHandCursor);
2602 QWidget::mouseReleaseEvent(evnt);
2606 void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
2608 int cv_event = -1, flags = 0;
2609 QPoint pt = evnt->pos();
2611 //icvmouseHandler: pass parameters for cv_event, flags
2612 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
2613 icvmouseProcessing(QPointF(pt), cv_event, flags);
2615 QWidget::mouseDoubleClickEvent(evnt);
2619 void DefaultViewPort::mouseMoveEvent(QMouseEvent* evnt)
2621 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
2622 QPoint pt = evnt->pos();
2624 //icvmouseHandler: pass parameters for cv_event, flags
2625 icvmouseHandler(evnt, mouse_move, cv_event, flags);
2626 icvmouseProcessing(QPointF(pt), cv_event, flags);
2628 if (param_matrixWorld.m11() > 1 && evnt->buttons() == Qt::LeftButton)
2630 QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11();
2631 positionGrabbing = evnt->pos();
2635 //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp)
2636 //the status bar will only be repaint when a click occurs.
2637 if (centralWidget->myStatusBar)
2638 viewport()->update();
2640 QWidget::mouseMoveEvent(evnt);
2644 void DefaultViewPort::paintEvent(QPaintEvent* evnt)
2646 QPainter myPainter(viewport());
2647 myPainter.setWorldTransform(param_matrixWorld);
2651 //Now disable matrixWorld for overlay display
2652 myPainter.setWorldMatrixEnabled(false);
2654 //in mode zoom/panning
2655 if (param_matrixWorld.m11() > 1)
2657 if (param_matrixWorld.m11() >= threshold_zoom_img_region)
2659 if (centralWidget->param_flags == CV_WINDOW_NORMAL)
2660 startDisplayInfo("WARNING: The values displayed are the resized image's values. If you want the original image's values, use CV_WINDOW_AUTOSIZE", 1000);
2662 drawImgRegion(&myPainter);
2665 drawViewOverview(&myPainter);
2668 //for information overlay
2670 drawInstructions(&myPainter);
2673 if (centralWidget->myStatusBar)
2676 QGraphicsView::paintEvent(evnt);
2680 void DefaultViewPort::stopDisplayInfo()
2682 timerDisplay->stop();
2687 inline bool DefaultViewPort::isSameSize(IplImage* img1, IplImage* img2)
2689 return img1->width == img2->width && img1->height == img2->height;
2693 void DefaultViewPort::controlImagePosition()
2695 qreal left, top, right, bottom;
2697 //after check top-left, bottom right corner to avoid getting "out" during zoom/panning
2698 param_matrixWorld.map(0,0,&left,&top);
2702 param_matrixWorld.translate(-left,0);
2707 param_matrixWorld.translate(0,-top);
2712 QSize sizeImage = size();
2713 param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom);
2714 if (right < sizeImage.width())
2716 param_matrixWorld.translate(sizeImage.width()-right,0);
2717 right = sizeImage.width();
2719 if (bottom < sizeImage.height())
2721 param_matrixWorld.translate(0,sizeImage.height()-bottom);
2722 bottom = sizeImage.height();
2725 //save corner position
2726 positionCorners.setTopLeft(QPoint(left,top));
2727 positionCorners.setBottomRight(QPoint(right,bottom));
2728 //save also the inv matrix
2729 matrixWorld_inv = param_matrixWorld.inverted();
2731 //viewport()->update();
2734 void DefaultViewPort::moveView(QPointF delta)
2736 param_matrixWorld.translate(delta.x(),delta.y());
2737 controlImagePosition();
2738 viewport()->update();
2741 //factor is -0.5 (zoom out) or 0.5 (zoom in)
2742 void DefaultViewPort::scaleView(qreal factor,QPointF center)
2744 factor/=5;//-0.1 <-> 0.1
2745 factor+=1;//0.9 <-> 1.1
2747 //limit zoom out ---
2748 if (param_matrixWorld.m11()==1 && factor < 1)
2751 if (param_matrixWorld.m11()*factor<1)
2752 factor = 1/param_matrixWorld.m11();
2755 //limit zoom int ---
2756 if (param_matrixWorld.m11()>100 && factor > 1)
2759 //inverse the transform
2761 matrixWorld_inv.map(center.x(),center.y(),&a,&b);
2763 param_matrixWorld.translate(a-factor*a,b-factor*b);
2764 param_matrixWorld.scale(factor,factor);
2766 controlImagePosition();
2769 if (centralWidget->myStatusBar)
2770 centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000);
2772 if (param_matrixWorld.m11()>1)
2773 setCursor(Qt::OpenHandCursor);
2779 //up, down, dclick, move
2780 void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)
2782 Qt::KeyboardModifiers modifiers = evnt->modifiers();
2783 Qt::MouseButtons buttons = evnt->buttons();
2786 if(modifiers & Qt::ShiftModifier)
2787 flags |= CV_EVENT_FLAG_SHIFTKEY;
2788 if(modifiers & Qt::ControlModifier)
2789 flags |= CV_EVENT_FLAG_CTRLKEY;
2790 if(modifiers & Qt::AltModifier)
2791 flags |= CV_EVENT_FLAG_ALTKEY;
2793 if(buttons & Qt::LeftButton)
2794 flags |= CV_EVENT_FLAG_LBUTTON;
2795 if(buttons & Qt::RightButton)
2796 flags |= CV_EVENT_FLAG_RBUTTON;
2797 if(buttons & Qt::MidButton)
2798 flags |= CV_EVENT_FLAG_MBUTTON;
2800 cv_event = CV_EVENT_MOUSEMOVE;
2801 switch(evnt->button())
2803 case Qt::LeftButton:
2804 cv_event = tableMouseButtons[category][0];
2805 flags |= CV_EVENT_FLAG_LBUTTON;
2807 case Qt::RightButton:
2808 cv_event = tableMouseButtons[category][1];
2809 flags |= CV_EVENT_FLAG_RBUTTON;
2812 cv_event = tableMouseButtons[category][2];
2813 flags |= CV_EVENT_FLAG_MBUTTON;
2820 void DefaultViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
2822 //to convert mouse coordinate
2824 matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy);
2826 mouseCoordinate.rx()=floor(pfx/ratioX);
2827 mouseCoordinate.ry()=floor(pfy/ratioY);
2830 on_mouse( cv_event, mouseCoordinate.x(),
2831 mouseCoordinate.y(), flags, on_mouse_param );
2835 QSize DefaultViewPort::sizeHint() const
2838 return QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2840 return QGraphicsView::sizeHint();
2844 void DefaultViewPort::draw2D(QPainter *painter)
2846 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888);
2847 painter->drawImage(QRect(0,0,viewport()->width(),viewport()->height()), image2Draw_qt, QRect(0,0, image2Draw_qt.width(), image2Draw_qt.height()) );
2850 //only if CV_8UC1 or CV_8UC3
2851 void DefaultViewPort::drawStatusBar()
2853 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2856 if (mouseCoordinate.x()>=0 &&
2857 mouseCoordinate.y()>=0 &&
2858 mouseCoordinate.x()<image2Draw_qt.width() &&
2859 mouseCoordinate.y()<image2Draw_qt.height())
2860 // if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0)
2862 QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate);
2864 if (nbChannelOriginImage==CV_8UC3 )
2866 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2867 .arg(mouseCoordinate.x())
2868 .arg(mouseCoordinate.y())+
2869 tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+
2870 tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+
2871 tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2])
2875 if (nbChannelOriginImage==CV_8UC1)
2877 //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed
2878 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2879 .arg(mouseCoordinate.x())
2880 .arg(mouseCoordinate.y())+
2881 tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue))
2887 //accept only CV_8UC1 and CV_8UC8 image for now
2888 void DefaultViewPort::drawImgRegion(QPainter *painter)
2891 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2894 qreal offsetX = param_matrixWorld.dx()/param_matrixWorld.m11();
2895 offsetX = offsetX - floor(offsetX);
2896 qreal offsetY = param_matrixWorld.dy()/param_matrixWorld.m11();
2897 offsetY = offsetY - floor(offsetY);
2899 QSize view = size();
2900 QVarLengthArray<QLineF, 30> linesX;
2901 for (qreal _x = offsetX*param_matrixWorld.m11(); _x < view.width(); _x += param_matrixWorld.m11() )
2902 linesX.append(QLineF(_x, 0, _x, view.height()));
2904 QVarLengthArray<QLineF, 30> linesY;
2905 for (qreal _y = offsetY*param_matrixWorld.m11(); _y < view.height(); _y += param_matrixWorld.m11() )
2906 linesY.append(QLineF(0, _y, view.width(), _y));
2909 QFont f = painter->font();
2910 int original_font_size = f.pointSize();
2912 //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2913 f.setPixelSize(10+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2914 painter->setFont(f);
2918 QPointF point1;//sorry, I do not know how to name it
2919 QPointF point2;//idem
2921 for (int j=-1;j<height()/param_matrixWorld.m11();j++)//-1 because display the pixels top rows left colums
2922 for (int i=-1;i<width()/param_matrixWorld.m11();i++)//-1
2924 point1.setX((i+offsetX)*param_matrixWorld.m11());
2925 point1.setY((j+offsetY)*param_matrixWorld.m11());
2927 matrixWorld_inv.map(point1.x(),point1.y(),&point2.rx(),&point2.ry());
2929 point2.rx()= (long) (point2.x() + 0.5);
2930 point2.ry()= (long) (point2.y() + 0.5);
2932 if (point2.x() >= 0 && point2.y() >= 0)
2933 rgbValue = image2Draw_qt_resized.pixel(QPoint(point2.x(),point2.y()));
2935 rgbValue = qRgb(0,0,0);
2937 if (nbChannelOriginImage==CV_8UC3)
2941 val = tr("%1 %2").arg(point2.x()).arg(point2.y());
2942 painter->setPen(QPen(Qt::black, 1));
2943 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
2944 Qt::AlignCenter, val);
2947 val = tr("%1").arg(qRed(rgbValue));
2948 painter->setPen(QPen(Qt::red, 1));
2949 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/3),
2950 Qt::AlignCenter, val);
2952 val = tr("%1").arg(qGreen(rgbValue));
2953 painter->setPen(QPen(Qt::green, 1));
2954 painter->drawText(QRect(point1.x(),point1.y()+param_matrixWorld.m11()/3,param_matrixWorld.m11(),param_matrixWorld.m11()/3),
2955 Qt::AlignCenter, val);
2957 val = tr("%1").arg(qBlue(rgbValue));
2958 painter->setPen(QPen(Qt::blue, 1));
2959 painter->drawText(QRect(point1.x(),point1.y()+2*param_matrixWorld.m11()/3,param_matrixWorld.m11(),param_matrixWorld.m11()/3),
2960 Qt::AlignCenter, val);
2964 if (nbChannelOriginImage==CV_8UC1)
2967 val = tr("%1").arg(qRed(rgbValue));
2968 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()),
2969 Qt::AlignCenter, val);
2973 painter->setPen(QPen(Qt::black, 1));
2974 painter->drawLines(linesX.data(), linesX.size());
2975 painter->drawLines(linesY.data(), linesY.size());
2978 f.setPointSize(original_font_size);
2979 painter->setFont(f);
2983 void DefaultViewPort::drawViewOverview(QPainter *painter)
2985 QSize viewSize = size();
2986 viewSize.scale ( 100, 100,Qt::KeepAspectRatio );
2988 const int margin = 5;
2990 //draw the image's location
2991 painter->setBrush(QColor(0, 0, 0, 127));
2992 painter->setPen(Qt::darkGreen);
2993 painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height()));
2995 //daw the view's location inside the image
2996 qreal ratioSize = 1/param_matrixWorld.m11();
2997 qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height());
2998 painter->setPen(Qt::darkBlue);
2999 painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin,
3000 -positionCorners.top()*ratioSize*ratioWindow,
3001 (viewSize.width()-1)*ratioSize,
3002 (viewSize.height()-1)*ratioSize)
3006 void DefaultViewPort::drawInstructions(QPainter *painter)
3008 QFontMetrics metrics = QFontMetrics(font());
3009 int border = qMax(4, metrics.leading());
3011 QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
3012 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3013 painter->setRenderHint(QPainter::TextAntialiasing);
3014 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3015 QColor(0, 0, 0, 127));
3016 painter->setPen(Qt::white);
3017 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3018 QColor(0, 0, 0, 127));
3020 painter->drawText((width() - qrect.width())/2, border,
3021 qrect.width(), qrect.height(),
3022 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3026 void DefaultViewPort::setSize(QSize /*size_*/)
3031 //////////////////////////////////////////////////////
3034 #ifdef HAVE_QT_OPENGL
3036 OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)
3045 OpenGlViewPort::~OpenGlViewPort()
3049 QWidget* OpenGlViewPort::getWidget()
3054 void OpenGlViewPort::setMouseCallBack(CvMouseCallback callback, void* param)
3056 mouseCallback = callback;
3060 void OpenGlViewPort::writeSettings(QSettings& /*settings*/)
3064 void OpenGlViewPort::readSettings(QSettings& /*settings*/)
3068 double OpenGlViewPort::getRatio()
3070 return (double)width() / height();
3073 void OpenGlViewPort::setRatio(int /*flags*/)
3077 void OpenGlViewPort::updateImage(const CvArr* /*arr*/)
3081 void OpenGlViewPort::startDisplayInfo(QString /*text*/, int /*delayms*/)
3085 void OpenGlViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
3087 glDrawCallback = callback;
3088 glDrawData = userdata;
3091 void OpenGlViewPort::makeCurrentOpenGlContext()
3096 void OpenGlViewPort::updateGl()
3098 QGLWidget::updateGL();
3101 void OpenGlViewPort::initializeGL()
3103 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3106 void OpenGlViewPort::resizeGL(int w, int h)
3108 glViewport(0, 0, w, h);
3111 void OpenGlViewPort::paintGL()
3113 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3116 glDrawCallback(glDrawData);
3119 void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)
3121 int cv_event = -1, flags = 0;
3122 QPoint pt = evnt->pos();
3124 icvmouseHandler(evnt, mouse_down, cv_event, flags);
3125 icvmouseProcessing(QPointF(pt), cv_event, flags);
3127 QGLWidget::mousePressEvent(evnt);
3131 void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)
3133 int cv_event = -1, flags = 0;
3134 QPoint pt = evnt->pos();
3136 icvmouseHandler(evnt, mouse_up, cv_event, flags);
3137 icvmouseProcessing(QPointF(pt), cv_event, flags);
3139 QGLWidget::mouseReleaseEvent(evnt);
3143 void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
3145 int cv_event = -1, flags = 0;
3146 QPoint pt = evnt->pos();
3148 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
3149 icvmouseProcessing(QPointF(pt), cv_event, flags);
3151 QGLWidget::mouseDoubleClickEvent(evnt);
3155 void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)
3157 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
3158 QPoint pt = evnt->pos();
3160 //icvmouseHandler: pass parameters for cv_event, flags
3161 icvmouseHandler(evnt, mouse_move, cv_event, flags);
3162 icvmouseProcessing(QPointF(pt), cv_event, flags);
3164 QGLWidget::mouseMoveEvent(evnt);
3167 void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)
3169 Qt::KeyboardModifiers modifiers = evnt->modifiers();
3170 Qt::MouseButtons buttons = evnt->buttons();
3173 if (modifiers & Qt::ShiftModifier)
3174 flags |= CV_EVENT_FLAG_SHIFTKEY;
3175 if (modifiers & Qt::ControlModifier)
3176 flags |= CV_EVENT_FLAG_CTRLKEY;
3177 if (modifiers & Qt::AltModifier)
3178 flags |= CV_EVENT_FLAG_ALTKEY;
3180 if (buttons & Qt::LeftButton)
3181 flags |= CV_EVENT_FLAG_LBUTTON;
3182 if (buttons & Qt::RightButton)
3183 flags |= CV_EVENT_FLAG_RBUTTON;
3184 if (buttons & Qt::MidButton)
3185 flags |= CV_EVENT_FLAG_MBUTTON;
3187 cv_event = CV_EVENT_MOUSEMOVE;
3188 switch (evnt->button())
3190 case Qt::LeftButton:
3191 cv_event = tableMouseButtons[category][0];
3192 flags |= CV_EVENT_FLAG_LBUTTON;
3195 case Qt::RightButton:
3196 cv_event = tableMouseButtons[category][1];
3197 flags |= CV_EVENT_FLAG_RBUTTON;
3201 cv_event = tableMouseButtons[category][2];
3202 flags |= CV_EVENT_FLAG_MBUTTON;
3211 void OpenGlViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
3214 mouseCallback(cv_event, pt.x(), pt.y(), flags, mouseData);
3218 QSize OpenGlViewPort::sizeHint() const
3220 if (size.width() > 0 && size.height() > 0)
3223 return QGLWidget::sizeHint();
3226 void OpenGlViewPort::setSize(QSize size_)