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 CV_IMPL void cvSetTrackbarMax(const char* name_bar, const char* window_name, int maxval)
661 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
664 t->slider->setMaximum(maxval);
670 /* assign callback for mouse events */
671 CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param)
673 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
676 CV_Error(CV_StsNullPtr, "NULL window handler");
678 w->setMouseCallBack(on_mouse, param);
683 CV_IMPL void cvShowImage(const char* name, const CvArr* arr)
686 guiMainThread = new GuiReceiver;
687 if (QThread::currentThread() != QApplication::instance()->thread()) {
689 QMetaObject::invokeMethod(guiMainThread,
691 autoBlockingConnection(),
692 Q_ARG(QString, QString(name)),
693 Q_ARG(void*, (void*)arr)
696 guiMainThread->showImage(QString(name), (void*)arr);
701 #ifdef HAVE_QT_OPENGL
703 CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
706 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
708 QMetaObject::invokeMethod(guiMainThread,
709 "setOpenGlDrawCallback",
710 autoBlockingConnection(),
711 Q_ARG(QString, QString(window_name)),
712 Q_ARG(void*, (void*)callback),
713 Q_ARG(void*, userdata));
717 CV_IMPL void cvSetOpenGlContext(const char* window_name)
720 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
722 QMetaObject::invokeMethod(guiMainThread,
724 autoBlockingConnection(),
725 Q_ARG(QString, QString(window_name)));
729 CV_IMPL void cvUpdateWindow(const char* window_name)
732 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
734 QMetaObject::invokeMethod(guiMainThread,
736 autoBlockingConnection(),
737 Q_ARG(QString, QString(window_name)));
743 double cvGetOpenGlProp_QT(const char* name)
749 QMetaObject::invokeMethod(guiMainThread,
751 autoBlockingConnection(),
752 Q_RETURN_ARG(double, result),
753 Q_ARG(QString, QString(name)));
760 //////////////////////////////////////////////////////
764 GuiReceiver::GuiReceiver() : bTimeOut(false), nb_windows(0)
766 doesExternalQAppExist = (QApplication::instance() != 0);
767 icvInitSystem(¶meterSystemC, parameterSystemV);
769 timer = new QTimer(this);
770 QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
771 timer->setSingleShot(true);
772 if ( doesExternalQAppExist ) {
773 moveToThread(QApplication::instance()->thread());
778 void GuiReceiver::isLastWindow()
780 if (--nb_windows <= 0)
782 delete guiMainThread;//delete global_control_panel too
783 guiMainThread = NULL;
785 if (!doesExternalQAppExist)
793 GuiReceiver::~GuiReceiver()
795 if (global_control_panel)
797 delete global_control_panel;
798 global_control_panel = NULL;
803 void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2)
808 mat = cvGetMat(arr, &stub);
810 int nbChannelOriginImage = cvGetElemType(mat);
811 if (nbChannelOriginImage != CV_8UC3) return; //for now, font works only with 8UC3
813 QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888);
815 CvFont* font = (CvFont*)arg2;
820 QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/);
821 f.setStyle((QFont::Style) font->font_face/*style*/);
822 f.setLetterSpacing(QFont::AbsoluteSpacing, font->dx/*spacing*/);
823 //cvScalar(blue_component, green_component, red_component[, alpha_component])
824 //Qt map non-transparent to 0xFF and transparent to 0
825 //OpenCV scalar is the reverse, so 255-font->color.val[3]
826 qp.setPen(QColor(font->color.val[2], font->color.val[1], font->color.val[0], 255 - font->color.val[3]));
829 qp.drawText(org, text);
834 void GuiReceiver::saveWindowParameters(QString name)
836 QPointer<CvWindow> w = icvFindWindowByName(name);
843 void GuiReceiver::loadWindowParameters(QString name)
845 QPointer<CvWindow> w = icvFindWindowByName(name);
852 double GuiReceiver::getRatioWindow(QString name)
854 QPointer<CvWindow> w = icvFindWindowByName(name);
859 return w->getRatio();
863 void GuiReceiver::setRatioWindow(QString name, double arg2)
865 QPointer<CvWindow> w = icvFindWindowByName( name.toLatin1().data() );
870 int flags = (int) arg2;
876 double GuiReceiver::getPropWindow(QString name)
878 QPointer<CvWindow> w = icvFindWindowByName(name);
883 return (double) w->getPropWindow();
887 void GuiReceiver::setPropWindow(QString name, double arg2)
889 QPointer<CvWindow> w = icvFindWindowByName(name);
894 int flags = (int) arg2;
896 w->setPropWindow(flags);
899 void GuiReceiver::setWindowTitle(QString name, QString title)
901 QPointer<CvWindow> w = icvFindWindowByName(name);
905 cvNamedWindow(name.toLatin1().data());
906 w = icvFindWindowByName(name);
912 w->setWindowTitle(title);
916 double GuiReceiver::isFullScreen(QString name)
918 QPointer<CvWindow> w = icvFindWindowByName(name);
923 return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL;
927 void GuiReceiver::toggleFullScreen(QString name, double arg2)
929 QPointer<CvWindow> w = icvFindWindowByName(name);
934 int flags = (int) arg2;
936 w->toggleFullScreen(flags);
940 void GuiReceiver::createWindow(QString name, int flags)
943 CV_Error(CV_StsNullPtr, "NULL session handler" );
945 // Check the name in the storage
946 if (icvFindWindowByName(name.toLatin1().data()))
952 new CvWindow(name, flags);
956 void GuiReceiver::timeOut()
962 void GuiReceiver::displayInfo(QString name, QString text, int delayms)
964 QPointer<CvWindow> w = icvFindWindowByName(name);
967 w->displayInfo(text, delayms);
971 void GuiReceiver::displayStatusBar(QString name, QString text, int delayms)
973 QPointer<CvWindow> w = icvFindWindowByName(name);
976 w->displayStatusBar(text, delayms);
980 void GuiReceiver::showImage(QString name, void* arr)
982 QPointer<CvWindow> w = icvFindWindowByName(name);
984 if (!w) //as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null
986 cvNamedWindow(name.toLatin1().data());
987 w = icvFindWindowByName(name);
991 return; // keep silence here.
997 mat = cvGetMat(arr, &stub);
999 cv::Mat im = cv::cvarrToMat(mat);
1000 cv::imshow(name.toUtf8().data(), im);
1004 w->updateImage(arr);
1012 void GuiReceiver::destroyWindow(QString name)
1015 QPointer<CvWindow> w = icvFindWindowByName(name);
1021 //in not-multiThreads mode, looks like the window is hidden but not deleted
1022 //so I do it manually
1023 //otherwise QApplication do it for me if the exec command was executed (in multiThread mode)
1030 void GuiReceiver::destroyAllWindow()
1033 CV_Error(CV_StsNullPtr, "NULL session handler" );
1037 // WARNING: this could even close windows from an external parent app
1038 //#TODO check externalQAppExists and in case it does, close windows carefully,
1039 // i.e. apply the className-check from below...
1040 qApp->closeAllWindows();
1044 bool isWidgetDeleted = true;
1045 while(isWidgetDeleted)
1047 isWidgetDeleted = false;
1048 QWidgetList list = QApplication::topLevelWidgets();
1049 for (int i = 0; i < list.count(); i++)
1051 QObject *obj = list.at(i);
1052 if (obj->metaObject()->className() == QString("CvWindow"))
1055 isWidgetDeleted = true;
1064 void GuiReceiver::moveWindow(QString name, int x, int y)
1066 QPointer<CvWindow> w = icvFindWindowByName(name);
1073 void GuiReceiver::resizeWindow(QString name, int width, int height)
1075 QPointer<CvWindow> w = icvFindWindowByName(name);
1080 w->setViewportSize(QSize(width, height));
1085 void GuiReceiver::enablePropertiesButtonEachWindow()
1087 //For each window, enable window property button
1088 foreach (QWidget* widget, QApplication::topLevelWidgets())
1090 if (widget->isWindow() && !widget->parentWidget()) //is a window without parent
1092 CvWinModel* temp = (CvWinModel*) widget;
1093 if (temp->type == type_CvWindow)
1095 CvWindow* w = (CvWindow*) widget;
1097 //active window properties button
1098 w->enablePropertiesButton();
1105 void GuiReceiver::addButton(QString button_name, int button_type, int initial_button_state, void* on_change, void* userdata)
1107 if (!global_control_panel)
1110 QPointer<CvButtonbar> b;
1112 if (global_control_panel->myLayout->count() == 0) //if that is the first button attach to the control panel, create a new button bar
1114 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1115 enablePropertiesButtonEachWindow();
1120 CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count() - 1);
1122 if (lastbar->type == type_CvTrackbar) //if last bar is a trackbar, create a new buttonbar, else, attach to the current bar
1123 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1125 b = (CvButtonbar*) lastbar;
1129 b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state);
1133 void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata)
1135 QBoxLayout *layout = NULL;
1136 QPointer<CvWindow> w;
1138 if (!window_name.isEmpty())
1140 w = icvFindWindowByName(window_name);
1147 if (global_control_panel)
1148 layout = global_control_panel->myLayout;
1151 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1153 if (t) //trackbar exists
1157 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1159 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1160 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1162 CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
1166 void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change)
1168 QBoxLayout *layout = NULL;
1169 QPointer<CvWindow> w;
1171 if (!window_name.isEmpty())
1173 w = icvFindWindowByName(window_name);
1180 if (global_control_panel)
1181 layout = global_control_panel->myLayout;
1184 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1186 if (t) //trackbar exists
1190 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1192 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1193 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1195 CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
1199 int GuiReceiver::start()
1201 return qApp->exec();
1205 void GuiReceiver::setOpenGlDrawCallback(QString name, void* callback, void* userdata)
1207 QPointer<CvWindow> w = icvFindWindowByName(name);
1210 w->setOpenGlDrawCallback((CvOpenGlDrawCallback) callback, userdata);
1213 void GuiReceiver::setOpenGlContext(QString name)
1215 QPointer<CvWindow> w = icvFindWindowByName(name);
1218 w->makeCurrentOpenGlContext();
1221 void GuiReceiver::updateWindow(QString name)
1223 QPointer<CvWindow> w = icvFindWindowByName(name);
1229 double GuiReceiver::isOpenGl(QString name)
1233 QPointer<CvWindow> w = icvFindWindowByName(name);
1236 result = (double) w->isOpenGl();
1242 //////////////////////////////////////////////////////
1246 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)
1249 callback2 = on_change;
1252 create(arg, name, value, _count);
1256 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)
1258 callback = on_change;
1262 create(arg, name, value, _count);
1266 void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)
1268 type = type_CvTrackbar;
1271 setObjectName(name_bar);
1274 slider = new QSlider(Qt::Horizontal);
1275 slider->setFocusPolicy(Qt::StrongFocus);
1276 slider->setMinimum(0);
1277 slider->setMaximum(_count);
1278 slider->setPageStep(5);
1279 slider->setValue(*value);
1280 slider->setTickPosition(QSlider::TicksBelow);
1283 //Change style of the Slider
1284 //slider->setStyleSheet(str_Trackbar_css);
1286 QFile qss(":/stylesheet-trackbar");
1287 if (qss.open(QFile::ReadOnly))
1289 slider->setStyleSheet(QLatin1String(qss.readAll()));
1294 //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?)
1295 //slider->setTickPosition(QSlider::TicksBelow);
1296 label = new QPushButton;
1297 label->setFlat(true);
1298 setLabel(slider->value());
1301 QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(update(int)));
1303 QObject::connect(label, SIGNAL(clicked()), this, SLOT(createDialog()));
1305 //label->setStyleSheet("QPushButton:disabled {color: black}");
1307 addWidget(label, Qt::AlignLeft);//name + value
1308 addWidget(slider, Qt::AlignCenter);//slider
1312 void CvTrackbar::createDialog()
1316 //crash if I access the values directly and give them to QInputDialog, so do a copy first.
1317 int value = slider->value();
1318 int step = slider->singleStep();
1319 int min = slider->minimum();
1320 int max = slider->maximum();
1323 #if QT_VERSION >= 0x040500
1324 QInputDialog::getInt
1326 QInputDialog::getInteger
1328 (this->parentWidget(),
1329 tr("Slider %1").arg(name_bar),
1338 slider->setValue(i);
1342 void CvTrackbar::update(int myvalue)
1346 *dataSlider = myvalue;
1355 callback2(myvalue, userdata);
1361 void CvTrackbar::setLabel(int myvalue)
1363 QString nameNormalized = name_bar.leftJustified( 10, ' ', true );
1364 QString valueMaximum = QString("%1").arg(slider->maximum());
1365 QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum);
1366 label->setText(str);
1370 //////////////////////////////////////////////////////
1374 //here CvButtonbar class
1375 CvButtonbar::CvButtonbar(QWidget* arg, QString arg2)
1377 type = type_CvButtonbar;
1380 setObjectName(name_bar);
1382 group_button = new QButtonGroup(this);
1386 void CvButtonbar::setLabel()
1388 QString nameNormalized = name_bar.leftJustified(10, ' ', true);
1389 label->setText(nameNormalized);
1393 void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state)
1395 QString button_name = name;
1397 if (button_name == "")
1398 button_name = tr("button %1").arg(this->count());
1400 QPointer<QAbstractButton> button;
1402 if (button_type == CV_PUSH_BUTTON)
1403 button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata);
1405 if (button_type == CV_CHECKBOX)
1406 button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state);
1408 if (button_type == CV_RADIOBOX)
1410 button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state);
1411 group_button->addButton(button);
1416 if (button_type == CV_PUSH_BUTTON)
1417 QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool)));
1419 QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool)));
1421 addWidget(button, Qt::AlignCenter);
1426 //////////////////////////////////////////////////////
1431 CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4)
1438 setObjectName(button_name);
1439 setText(button_name);
1446 void CvPushButton::callCallBack(bool checked)
1449 callback(checked, userdata);
1453 CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1460 setObjectName(button_name);
1461 setCheckState((initial_button_state == 1 ? Qt::Checked : Qt::Unchecked));
1462 setText(button_name);
1469 void CvCheckBox::callCallBack(bool checked)
1472 callback(checked, userdata);
1476 CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1483 setObjectName(button_name);
1484 setChecked(initial_button_state);
1485 setText(button_name);
1491 void CvRadioButton::callCallBack(bool checked)
1494 callback(checked, userdata);
1498 //////////////////////////////////////////////////////
1502 //here CvWinProperties class
1503 CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)
1505 //setParent(parent);
1506 type = type_CvWinProperties;
1507 setWindowFlags(Qt::Tool);
1508 setContentsMargins(0, 0, 0, 0);
1509 setWindowTitle(name_paraWindow);
1510 setObjectName(name_paraWindow);
1513 myLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1514 myLayout->setObjectName(QString::fromUtf8("boxLayout"));
1515 myLayout->setContentsMargins(0, 0, 0, 0);
1516 myLayout->setSpacing(0);
1517 myLayout->setMargin(0);
1518 myLayout->setSizeConstraint(QLayout::SetFixedSize);
1519 setLayout(myLayout);
1525 void CvWinProperties::closeEvent(QCloseEvent* e)
1527 e->accept(); //intersept the close event (not sure I really need it)
1528 //an hide event is also sent. I will intercept it and do some processing
1532 void CvWinProperties::showEvent(QShowEvent* evnt)
1534 //why -1,-1 ?: do this trick because the first time the code is run,
1535 //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).
1536 //then hide will save the last position and thus, we want to retreive it (event accepted).
1537 QPoint mypos(-1, -1);
1538 QSettings settings("OpenCV2", objectName());
1539 mypos = settings.value("pos", mypos).toPoint();
1553 void CvWinProperties::hideEvent(QHideEvent* evnt)
1555 QSettings settings("OpenCV2", objectName());
1556 settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)
1561 CvWinProperties::~CvWinProperties()
1563 //clear the setting pos
1564 QSettings settings("OpenCV2", objectName());
1565 settings.remove("pos");
1569 //////////////////////////////////////////////////////
1573 CvWindow::CvWindow(QString name, int arg2)
1575 type = type_CvWindow;
1577 param_flags = arg2 & 0x0000000F;
1578 param_gui_mode = arg2 & 0x000000F0;
1579 param_ratio_mode = arg2 & 0x00000F00;
1581 //setAttribute(Qt::WA_DeleteOnClose); //in other case, does not release memory
1582 setContentsMargins(0, 0, 0, 0);
1583 setWindowTitle(name);
1584 setObjectName(name);
1586 setFocus( Qt::PopupFocusReason ); //#1695 arrow keys are not received without the explicit focus
1589 setMinimumSize(1, 1);
1591 //1: create control panel
1592 if (!global_control_panel)
1593 global_control_panel = createParameterWindow();
1597 createGlobalLayout();
1600 #ifndef HAVE_QT_OPENGL
1601 if (arg2 & CV_WINDOW_OPENGL)
1602 CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
1603 mode_display = CV_MODE_NORMAL;
1605 mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
1606 if (mode_display == CV_MODE_OPENGL)
1607 param_gui_mode = CV_GUI_NORMAL;
1611 //4: shortcuts and actions
1612 //5: toolBar and statusbar
1613 if (param_gui_mode == CV_GUI_EXPANDED)
1622 //Now attach everything
1624 myGlobalLayout->addWidget(myToolBar, Qt::AlignCenter);
1626 myGlobalLayout->addWidget(myView->getWidget(), Qt::AlignCenter);
1628 myGlobalLayout->addLayout(myBarLayout, Qt::AlignCenter);
1631 myGlobalLayout->addWidget(myStatusBar, Qt::AlignCenter);
1633 setLayout(myGlobalLayout);
1638 CvWindow::~CvWindow()
1641 guiMainThread->isLastWindow();
1645 void CvWindow::setMouseCallBack(CvMouseCallback callback, void* param)
1647 myView->setMouseCallBack(callback, param);
1651 void CvWindow::writeSettings()
1653 //organisation and application's name
1654 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1656 settings.setValue("pos", pos());
1657 settings.setValue("size", size());
1658 settings.setValue("mode_resize" ,param_flags);
1659 settings.setValue("mode_gui", param_gui_mode);
1661 myView->writeSettings(settings);
1663 icvSaveTrackbars(&settings);
1665 if (global_control_panel)
1667 icvSaveControlPanel();
1668 settings.setValue("posPanel", global_control_panel->pos());
1674 //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars)
1675 void CvWindow::readSettings()
1677 //organisation and application's name
1678 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1680 QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();
1681 QSize _size = settings.value("size", QSize(400, 400)).toSize();
1683 param_flags = settings.value("mode_resize", param_flags).toInt();
1684 param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();
1686 param_flags = settings.value("mode_resize", param_flags).toInt();
1688 myView->readSettings(settings);
1691 icvLoadTrackbars(&settings);
1696 if (global_control_panel)
1698 icvLoadControlPanel();
1699 global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint());
1704 double CvWindow::getRatio()
1706 return myView->getRatio();
1710 void CvWindow::setRatio(int flags)
1712 myView->setRatio(flags);
1716 int CvWindow::getPropWindow()
1722 void CvWindow::setPropWindow(int flags)
1724 if (param_flags == flags) //nothing to do
1729 case CV_WINDOW_NORMAL:
1730 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1731 param_flags = flags;
1735 case CV_WINDOW_AUTOSIZE:
1736 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1737 param_flags = flags;
1746 void CvWindow::toggleFullScreen(int flags)
1748 if (isFullScreen() && flags == CV_WINDOW_NORMAL)
1755 if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN)
1764 void CvWindow::updateImage(void* arr)
1766 myView->updateImage(arr);
1770 void CvWindow::displayInfo(QString text, int delayms)
1772 myView->startDisplayInfo(text, delayms);
1776 void CvWindow::displayStatusBar(QString text, int delayms)
1779 myStatusBar->showMessage(text, delayms);
1783 void CvWindow::enablePropertiesButton()
1785 if (!vect_QActions.empty())
1786 vect_QActions[9]->setDisabled(false);
1790 CvButtonbar* CvWindow::createButtonBar(QString name_bar)
1792 QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel, name_bar);
1793 t->setAlignment(Qt::AlignHCenter);
1795 QPointer<QBoxLayout> myLayout = global_control_panel->myLayout;
1797 myLayout->insertLayout(myLayout->count(), t);
1803 void CvWindow::addSlider(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback on_change)
1805 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change);
1806 t->setAlignment(Qt::AlignHCenter);
1808 QPointer<QBoxLayout> myLayout;
1812 myLayout = w->myBarLayout;
1816 myLayout = global_control_panel->myLayout;
1818 //if first one, enable control panel
1819 if (myLayout->count() == 0)
1820 guiMainThread->enablePropertiesButtonEachWindow();
1823 myLayout->insertLayout(myLayout->count(), t);
1827 void CvWindow::addSlider2(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata)
1829 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change, userdata);
1830 t->setAlignment(Qt::AlignHCenter);
1832 QPointer<QBoxLayout> myLayout;
1836 myLayout = w->myBarLayout;
1840 myLayout = global_control_panel->myLayout;
1842 //if first one, enable control panel
1843 if (myLayout->count() == 0)
1844 guiMainThread->enablePropertiesButtonEachWindow();
1847 myLayout->insertLayout(myLayout->count(), t);
1851 void CvWindow::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
1853 myView->setOpenGlDrawCallback(callback, userdata);
1857 void CvWindow::makeCurrentOpenGlContext()
1859 myView->makeCurrentOpenGlContext();
1863 void CvWindow::updateGl()
1869 bool CvWindow::isOpenGl()
1871 return mode_display == CV_MODE_OPENGL;
1875 void CvWindow::setViewportSize(QSize _size)
1877 myView->getWidget()->resize(_size);
1878 myView->setSize(_size);
1882 void CvWindow::createBarLayout()
1884 myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1885 myBarLayout->setObjectName(QString::fromUtf8("barLayout"));
1886 myBarLayout->setContentsMargins(0, 0, 0, 0);
1887 myBarLayout->setSpacing(0);
1888 myBarLayout->setMargin(0);
1892 void CvWindow::createGlobalLayout()
1894 myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1895 myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout"));
1896 myGlobalLayout->setContentsMargins(0, 0, 0, 0);
1897 myGlobalLayout->setSpacing(0);
1898 myGlobalLayout->setMargin(0);
1899 setMinimumSize(1, 1);
1901 if (param_flags == CV_WINDOW_AUTOSIZE)
1902 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1903 else if (param_flags == CV_WINDOW_NORMAL)
1904 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1908 void CvWindow::createView()
1910 #ifdef HAVE_QT_OPENGL
1912 myView = new OpenGlViewPort(this);
1915 myView = new DefaultViewPort(this, param_ratio_mode);
1919 void CvWindow::createActions()
1921 vect_QActions.resize(10);
1923 QWidget* view = myView->getWidget();
1925 //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually
1926 vect_QActions[0] = new QAction(QIcon(":/left-icon"), "Panning left (CTRL+arrowLEFT)", this);
1927 vect_QActions[0]->setIconVisibleInMenu(true);
1928 QObject::connect(vect_QActions[0], SIGNAL(triggered()), view, SLOT(siftWindowOnLeft()));
1930 vect_QActions[1] = new QAction(QIcon(":/right-icon"), "Panning right (CTRL+arrowRIGHT)", this);
1931 vect_QActions[1]->setIconVisibleInMenu(true);
1932 QObject::connect(vect_QActions[1], SIGNAL(triggered()), view, SLOT(siftWindowOnRight()));
1934 vect_QActions[2] = new QAction(QIcon(":/up-icon"), "Panning up (CTRL+arrowUP)", this);
1935 vect_QActions[2]->setIconVisibleInMenu(true);
1936 QObject::connect(vect_QActions[2], SIGNAL(triggered()), view, SLOT(siftWindowOnUp()));
1938 vect_QActions[3] = new QAction(QIcon(":/down-icon"), "Panning down (CTRL+arrowDOWN)", this);
1939 vect_QActions[3]->setIconVisibleInMenu(true);
1940 QObject::connect(vect_QActions[3], SIGNAL(triggered()), view, SLOT(siftWindowOnDown()) );
1942 vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"), "Zoom x1 (CTRL+P)", this);
1943 vect_QActions[4]->setIconVisibleInMenu(true);
1944 QObject::connect(vect_QActions[4], SIGNAL(triggered()), view, SLOT(resetZoom()));
1946 vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"), tr("Zoom x%1 (see label) (CTRL+X)").arg(threshold_zoom_img_region), this);
1947 vect_QActions[5]->setIconVisibleInMenu(true);
1948 QObject::connect(vect_QActions[5], SIGNAL(triggered()), view, SLOT(imgRegion()));
1950 vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"), "Zoom in (CTRL++)", this);
1951 vect_QActions[6]->setIconVisibleInMenu(true);
1952 QObject::connect(vect_QActions[6], SIGNAL(triggered()), view, SLOT(ZoomIn()));
1954 vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"), "Zoom out (CTRL+-)", this);
1955 vect_QActions[7]->setIconVisibleInMenu(true);
1956 QObject::connect(vect_QActions[7], SIGNAL(triggered()), view, SLOT(ZoomOut()));
1958 vect_QActions[8] = new QAction(QIcon(":/save-icon"), "Save current image (CTRL+S)", this);
1959 vect_QActions[8]->setIconVisibleInMenu(true);
1960 QObject::connect(vect_QActions[8], SIGNAL(triggered()), view, SLOT(saveView()));
1962 vect_QActions[9] = new QAction(QIcon(":/properties-icon"), "Display properties window (CTRL+P)", this);
1963 vect_QActions[9]->setIconVisibleInMenu(true);
1964 QObject::connect(vect_QActions[9], SIGNAL(triggered()), this, SLOT(displayPropertiesWin()));
1966 if (global_control_panel->myLayout->count() == 0)
1967 vect_QActions[9]->setDisabled(true);
1971 void CvWindow::createShortcuts()
1973 vect_QShortcuts.resize(10);
1975 QWidget* view = myView->getWidget();
1977 vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this);
1978 QObject::connect(vect_QShortcuts[0], SIGNAL(activated()), view, SLOT(siftWindowOnLeft()));
1980 vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this);
1981 QObject::connect(vect_QShortcuts[1], SIGNAL(activated()), view, SLOT(siftWindowOnRight()));
1983 vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this);
1984 QObject::connect(vect_QShortcuts[2], SIGNAL(activated()), view, SLOT(siftWindowOnUp()));
1986 vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this);
1987 QObject::connect(vect_QShortcuts[3], SIGNAL(activated()), view, SLOT(siftWindowOnDown()));
1989 vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this);
1990 QObject::connect(vect_QShortcuts[4], SIGNAL(activated()), view, SLOT(resetZoom()));
1992 vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this);
1993 QObject::connect(vect_QShortcuts[5], SIGNAL(activated()), view, SLOT(imgRegion()));
1995 vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this);
1996 QObject::connect(vect_QShortcuts[6], SIGNAL(activated()), view, SLOT(ZoomIn()));
1998 vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this);
1999 QObject::connect(vect_QShortcuts[7], SIGNAL(activated()), view, SLOT(ZoomOut()));
2001 vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this);
2002 QObject::connect(vect_QShortcuts[8], SIGNAL(activated()), view, SLOT(saveView()));
2004 vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this);
2005 QObject::connect(vect_QShortcuts[9], SIGNAL(activated()), this, SLOT(displayPropertiesWin()));
2009 void CvWindow::createToolBar()
2011 myToolBar = new QToolBar(this);
2012 myToolBar->setFloatable(false); //is not a window
2013 myToolBar->setFixedHeight(28);
2014 myToolBar->setMinimumWidth(1);
2016 foreach (QAction *a, vect_QActions)
2017 myToolBar->addAction(a);
2021 void CvWindow::createStatusBar()
2023 myStatusBar = new QStatusBar(this);
2024 myStatusBar->setSizeGripEnabled(false);
2025 myStatusBar->setFixedHeight(20);
2026 myStatusBar->setMinimumWidth(1);
2027 myStatusBar_msg = new QLabel;
2029 //I comment this because if we change the style, myview (the picture)
2030 //will not be the correct size anymore (will lost 2 pixel because of the borders)
2032 //myStatusBar_msg->setFrameStyle(QFrame::Raised);
2034 myStatusBar_msg->setAlignment(Qt::AlignHCenter);
2035 myStatusBar->addWidget(myStatusBar_msg);
2039 void CvWindow::hideTools()
2045 myStatusBar->hide();
2047 if (global_control_panel)
2048 global_control_panel->hide();
2052 void CvWindow::showTools()
2058 myStatusBar->show();
2062 CvWinProperties* CvWindow::createParameterWindow()
2064 QString name_paraWindow = QFileInfo(QApplication::applicationFilePath()).fileName() + " settings";
2066 CvWinProperties* result = new CvWinProperties(name_paraWindow, guiMainThread);
2072 void CvWindow::displayPropertiesWin()
2074 if (global_control_panel->isHidden())
2075 global_control_panel->show();
2077 global_control_panel->hide();
2081 //Need more test here !
2082 void CvWindow::keyPressEvent(QKeyEvent *evnt)
2084 //see http://doc.trolltech.com/4.6/qt.html#Key-enum
2085 int key = evnt->key();
2087 Qt::Key qtkey = static_cast<Qt::Key>(key);
2088 char asciiCode = QTest::keyToAscii(qtkey);
2090 key = static_cast<int>(asciiCode);
2092 key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend
2094 //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions
2095 if (evnt->modifiers() != Qt::ControlModifier)
2100 key_pressed.wakeAll();
2104 QWidget::keyPressEvent(evnt);
2108 void CvWindow::icvLoadControlPanel()
2110 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");
2112 int bsize = settings.beginReadArray("bars");
2114 if (bsize == global_control_panel->myLayout->layout()->count())
2116 for (int i = 0; i < bsize; ++i)
2118 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2119 settings.setArrayIndex(i);
2120 if (t->type == type_CvTrackbar)
2122 if (t->name_bar == settings.value("namebar").toString())
2124 ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt());
2127 if (t->type == type_CvButtonbar)
2129 int subsize = settings.beginReadArray(QString("buttonbar")+i);
2131 if ( subsize == ((CvButtonbar*)t)->layout()->count() )
2132 icvLoadButtonbar((CvButtonbar*)t,&settings);
2134 settings.endArray();
2139 settings.endArray();
2143 void CvWindow::icvSaveControlPanel()
2145 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel");
2147 settings.beginWriteArray("bars");
2149 for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i)
2151 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2152 settings.setArrayIndex(i);
2153 if (t->type == type_CvTrackbar)
2155 settings.setValue("namebar", QString(t->name_bar));
2156 settings.setValue("valuebar",((CvTrackbar*)t)->slider->value());
2158 if (t->type == type_CvButtonbar)
2160 settings.beginWriteArray(QString("buttonbar")+i);
2161 icvSaveButtonbar((CvButtonbar*)t,&settings);
2162 settings.endArray();
2166 settings.endArray();
2170 void CvWindow::icvSaveButtonbar(CvButtonbar* b, QSettings* settings)
2172 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2174 settings->setArrayIndex(i);
2176 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2177 QString myclass(QLatin1String(temp->metaObject()->className()));
2179 if (myclass == "CvPushButton")
2181 CvPushButton* button = (CvPushButton*) temp;
2182 settings->setValue("namebutton", button->text());
2183 settings->setValue("valuebutton", int(button->isChecked()));
2185 else if (myclass == "CvCheckBox")
2187 CvCheckBox* button = (CvCheckBox*) temp;
2188 settings->setValue("namebutton", button->text());
2189 settings->setValue("valuebutton", int(button->isChecked()));
2191 else if (myclass == "CvRadioButton")
2193 CvRadioButton* button = (CvRadioButton*) temp;
2194 settings->setValue("namebutton", button->text());
2195 settings->setValue("valuebutton", int(button->isChecked()));
2201 void CvWindow::icvLoadButtonbar(CvButtonbar* b, QSettings* settings)
2203 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2205 settings->setArrayIndex(i);
2207 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2208 QString myclass(QLatin1String(temp->metaObject()->className()));
2210 if (myclass == "CvPushButton")
2212 CvPushButton* button = (CvPushButton*) temp;
2214 if (button->text() == settings->value("namebutton").toString())
2215 button->setChecked(settings->value("valuebutton").toInt());
2217 else if (myclass == "CvCheckBox")
2219 CvCheckBox* button = (CvCheckBox*) temp;
2221 if (button->text() == settings->value("namebutton").toString())
2222 button->setChecked(settings->value("valuebutton").toInt());
2224 else if (myclass == "CvRadioButton")
2226 CvRadioButton* button = (CvRadioButton*) temp;
2228 if (button->text() == settings->value("namebutton").toString())
2229 button->setChecked(settings->value("valuebutton").toInt());
2236 void CvWindow::icvLoadTrackbars(QSettings* settings)
2238 int bsize = settings->beginReadArray("trackbars");
2240 //trackbar are saved in the same order, so no need to use icvFindTrackbarByName
2242 if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)
2244 for (int i = 0; i < bsize; ++i)
2246 settings->setArrayIndex(i);
2248 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2250 if (t->name_bar == settings->value("name").toString())
2251 t->slider->setValue(settings->value("value").toInt());
2256 settings->endArray();
2260 void CvWindow::icvSaveTrackbars(QSettings* settings)
2262 settings->beginWriteArray("trackbars");
2264 for (int i = 0; i < myBarLayout->layout()->count(); ++i)
2266 settings->setArrayIndex(i);
2268 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2270 settings->setValue("name", t->name_bar);
2271 settings->setValue("value", t->slider->value());
2274 settings->endArray();
2278 //////////////////////////////////////////////////////
2282 DefaultViewPort::DefaultViewPort(CvWindow* arg, int arg2) : QGraphicsView(arg), image2Draw_mat(0)
2284 centralWidget = arg;
2285 param_keepRatio = arg2;
2287 setContentsMargins(0, 0, 0, 0);
2288 setMinimumSize(1, 1);
2289 setAlignment(Qt::AlignHCenter);
2291 setObjectName(QString::fromUtf8("graphicsView"));
2293 timerDisplay = new QTimer(this);
2294 timerDisplay->setSingleShot(true);
2295 connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo()));
2298 positionGrabbing = QPointF(0, 0);
2299 positionCorners = QRect(0, 0, size().width(), size().height());
2303 mouseCoordinate = QPoint(-1, -1);
2306 setStyleSheet( "QGraphicsView { border-style: none; }" );
2308 image2Draw_mat = cvCreateMat(viewport()->height(), viewport()->width(), CV_8UC3);
2309 cvZero(image2Draw_mat);
2311 nbChannelOriginImage = 0;
2313 setInteractive(false);
2314 setMouseTracking(true); //receive mouse event everytime
2318 DefaultViewPort::~DefaultViewPort()
2321 cvReleaseMat(&image2Draw_mat);
2325 QWidget* DefaultViewPort::getWidget()
2331 void DefaultViewPort::setMouseCallBack(CvMouseCallback m, void* param)
2335 on_mouse_param = param;
2338 void DefaultViewPort::writeSettings(QSettings& settings)
2340 settings.setValue("matrix_view.m11", param_matrixWorld.m11());
2341 settings.setValue("matrix_view.m12", param_matrixWorld.m12());
2342 settings.setValue("matrix_view.m13", param_matrixWorld.m13());
2343 settings.setValue("matrix_view.m21", param_matrixWorld.m21());
2344 settings.setValue("matrix_view.m22", param_matrixWorld.m22());
2345 settings.setValue("matrix_view.m23", param_matrixWorld.m23());
2346 settings.setValue("matrix_view.m31", param_matrixWorld.m31());
2347 settings.setValue("matrix_view.m32", param_matrixWorld.m32());
2348 settings.setValue("matrix_view.m33", param_matrixWorld.m33());
2352 void DefaultViewPort::readSettings(QSettings& settings)
2354 qreal m11 = settings.value("matrix_view.m11", param_matrixWorld.m11()).toDouble();
2355 qreal m12 = settings.value("matrix_view.m12", param_matrixWorld.m12()).toDouble();
2356 qreal m13 = settings.value("matrix_view.m13", param_matrixWorld.m13()).toDouble();
2357 qreal m21 = settings.value("matrix_view.m21", param_matrixWorld.m21()).toDouble();
2358 qreal m22 = settings.value("matrix_view.m22", param_matrixWorld.m22()).toDouble();
2359 qreal m23 = settings.value("matrix_view.m23", param_matrixWorld.m23()).toDouble();
2360 qreal m31 = settings.value("matrix_view.m31", param_matrixWorld.m31()).toDouble();
2361 qreal m32 = settings.value("matrix_view.m32", param_matrixWorld.m32()).toDouble();
2362 qreal m33 = settings.value("matrix_view.m33", param_matrixWorld.m33()).toDouble();
2364 param_matrixWorld = QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33);
2368 double DefaultViewPort::getRatio()
2370 return param_keepRatio;
2374 void DefaultViewPort::setRatio(int flags)
2376 if (getRatio() == flags) //nothing to do
2380 if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO)
2382 centralWidget->param_ratio_mode = flags;
2383 param_keepRatio = flags;
2385 viewport()->update();
2390 void DefaultViewPort::updateImage(const CvArr* arr)
2397 if (CV_IS_IMAGE_HDR(arr))
2398 origin = ((IplImage*)arr)->origin;
2400 mat = cvGetMat(arr, &stub);
2402 if (!image2Draw_mat || !CV_ARE_SIZES_EQ(image2Draw_mat, mat))
2405 cvReleaseMat(&image2Draw_mat);
2407 //the image in ipl (to do a deep copy with cvCvtColor)
2408 image2Draw_mat = cvCreateMat(mat->rows, mat->cols, CV_8UC3);
2409 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows, image2Draw_mat->step, QImage::Format_RGB888);
2411 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2412 ratioX = width() / float(image2Draw_mat->cols);
2413 ratioY = height() / float(image2Draw_mat->rows);
2417 nbChannelOriginImage = cvGetElemType(mat);
2419 cvConvertImage(mat, image2Draw_mat, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB);
2421 viewport()->update();
2425 void DefaultViewPort::startDisplayInfo(QString text, int delayms)
2427 if (timerDisplay->isActive())
2431 if (delayms > 0) timerDisplay->start(delayms);
2436 void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
2438 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2442 void DefaultViewPort::makeCurrentOpenGlContext()
2444 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2448 void DefaultViewPort::updateGl()
2450 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2454 //Note: move 2 percent of the window
2455 void DefaultViewPort::siftWindowOnLeft()
2457 float delta = 2 * width() / (100.0 * param_matrixWorld.m11());
2458 moveView(QPointF(delta, 0));
2462 //Note: move 2 percent of the window
2463 void DefaultViewPort::siftWindowOnRight()
2465 float delta = -2 * width() / (100.0 * param_matrixWorld.m11());
2466 moveView(QPointF(delta, 0));
2470 //Note: move 2 percent of the window
2471 void DefaultViewPort::siftWindowOnUp()
2473 float delta = 2 * height() / (100.0 * param_matrixWorld.m11());
2474 moveView(QPointF(0, delta));
2478 //Note: move 2 percent of the window
2479 void DefaultViewPort::siftWindowOnDown()
2481 float delta = -2 * height() / (100.0 * param_matrixWorld.m11());
2482 moveView(QPointF(0, delta));
2486 void DefaultViewPort::imgRegion()
2488 scaleView((threshold_zoom_img_region / param_matrixWorld.m11() - 1) * 5, QPointF(size().width() / 2, size().height() / 2));
2492 void DefaultViewPort::resetZoom()
2494 param_matrixWorld.reset();
2495 controlImagePosition();
2499 void DefaultViewPort::ZoomIn()
2501 scaleView(0.5, QPointF(size().width() / 2, size().height() / 2));
2505 void DefaultViewPort::ZoomOut()
2507 scaleView(-0.5, QPointF(size().width() / 2, size().height() / 2));
2511 //can save as JPG, JPEG, BMP, PNG
2512 void DefaultViewPort::saveView()
2514 QDate date_d = QDate::currentDate();
2515 QString date_s = date_d.toString("dd.MM.yyyy");
2516 QString name_s = centralWidget->windowTitle() + "_screenshot_" + date_s;
2518 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s + ".png", tr("Images (*.png *.jpg *.bmp *.jpeg)"));
2520 if (!fileName.isEmpty()) //save the picture
2522 QString extension = fileName.right(3);
2524 // Create a new pixmap to render the viewport into
2525 QPixmap viewportPixmap(viewport()->size());
2526 viewport()->render(&viewportPixmap);
2529 if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
2531 viewportPixmap.save(fileName, "PNG");
2535 if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
2537 viewportPixmap.save(fileName, "JPG");
2541 if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
2543 viewportPixmap.save(fileName, "BMP");
2547 if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
2549 viewportPixmap.save(fileName, "JPEG");
2553 CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
2558 void DefaultViewPort::contextMenuEvent(QContextMenuEvent* evnt)
2560 if (centralWidget->vect_QActions.size() > 0)
2564 foreach (QAction *a, centralWidget->vect_QActions)
2567 menu.exec(evnt->globalPos());
2572 void DefaultViewPort::resizeEvent(QResizeEvent* evnt)
2574 controlImagePosition();
2576 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2577 ratioX = width() / float(image2Draw_mat->cols);
2578 ratioY = height() / float(image2Draw_mat->rows);
2580 if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio
2582 QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2583 newSize.scale(evnt->size(), Qt::KeepAspectRatio);
2585 //imageWidth/imageHeight = newWidth/newHeight +/- epsilon
2586 //ratioX = ratioY +/- epsilon
2587 //||ratioX - ratioY|| = epsilon
2588 if (fabs(ratioX - ratioY) * 100 > ratioX) //avoid infinity loop / epsilon = 1% of ratioX
2592 //move to the middle
2593 //newSize get the delta offset to place the picture in the middle of its parent
2594 newSize = (evnt->size() - newSize) / 2;
2596 //if the toolbar is displayed, avoid drawing myview on top of it
2597 if (centralWidget->myToolBar)
2598 if(!centralWidget->myToolBar->isHidden())
2599 newSize += QSize(0, centralWidget->myToolBar->height());
2601 move(newSize.width(), newSize.height());
2605 return QGraphicsView::resizeEvent(evnt);
2609 void DefaultViewPort::wheelEvent(QWheelEvent* evnt)
2611 scaleView(evnt->delta() / 240.0, evnt->pos());
2612 viewport()->update();
2616 void DefaultViewPort::mousePressEvent(QMouseEvent* evnt)
2618 int cv_event = -1, flags = 0;
2619 QPoint pt = evnt->pos();
2621 //icvmouseHandler: pass parameters for cv_event, flags
2622 icvmouseHandler(evnt, mouse_down, cv_event, flags);
2623 icvmouseProcessing(QPointF(pt), cv_event, flags);
2625 if (param_matrixWorld.m11()>1)
2627 setCursor(Qt::ClosedHandCursor);
2628 positionGrabbing = evnt->pos();
2631 QWidget::mousePressEvent(evnt);
2635 void DefaultViewPort::mouseReleaseEvent(QMouseEvent* evnt)
2637 int cv_event = -1, flags = 0;
2638 QPoint pt = evnt->pos();
2640 //icvmouseHandler: pass parameters for cv_event, flags
2641 icvmouseHandler(evnt, mouse_up, cv_event, flags);
2642 icvmouseProcessing(QPointF(pt), cv_event, flags);
2644 if (param_matrixWorld.m11()>1)
2645 setCursor(Qt::OpenHandCursor);
2647 QWidget::mouseReleaseEvent(evnt);
2651 void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
2653 int cv_event = -1, flags = 0;
2654 QPoint pt = evnt->pos();
2656 //icvmouseHandler: pass parameters for cv_event, flags
2657 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
2658 icvmouseProcessing(QPointF(pt), cv_event, flags);
2660 QWidget::mouseDoubleClickEvent(evnt);
2664 void DefaultViewPort::mouseMoveEvent(QMouseEvent* evnt)
2666 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
2667 QPoint pt = evnt->pos();
2669 //icvmouseHandler: pass parameters for cv_event, flags
2670 icvmouseHandler(evnt, mouse_move, cv_event, flags);
2671 icvmouseProcessing(QPointF(pt), cv_event, flags);
2673 if (param_matrixWorld.m11() > 1 && evnt->buttons() == Qt::LeftButton)
2675 QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11();
2676 positionGrabbing = evnt->pos();
2680 //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp)
2681 //the status bar will only be repaint when a click occurs.
2682 if (centralWidget->myStatusBar)
2683 viewport()->update();
2685 QWidget::mouseMoveEvent(evnt);
2689 void DefaultViewPort::paintEvent(QPaintEvent* evnt)
2691 QPainter myPainter(viewport());
2692 myPainter.setWorldTransform(param_matrixWorld);
2696 //Now disable matrixWorld for overlay display
2697 myPainter.setWorldMatrixEnabled(false);
2699 //overlay pixel values if zoomed in far enough
2700 if (param_matrixWorld.m11()*ratioX >= threshold_zoom_img_region &&
2701 param_matrixWorld.m11()*ratioY >= threshold_zoom_img_region)
2703 drawImgRegion(&myPainter);
2706 //in mode zoom/panning
2707 if (param_matrixWorld.m11() > 1)
2709 drawViewOverview(&myPainter);
2712 //for information overlay
2714 drawInstructions(&myPainter);
2717 if (centralWidget->myStatusBar)
2720 QGraphicsView::paintEvent(evnt);
2724 void DefaultViewPort::stopDisplayInfo()
2726 timerDisplay->stop();
2731 inline bool DefaultViewPort::isSameSize(IplImage* img1, IplImage* img2)
2733 return img1->width == img2->width && img1->height == img2->height;
2737 void DefaultViewPort::controlImagePosition()
2739 qreal left, top, right, bottom;
2741 //after check top-left, bottom right corner to avoid getting "out" during zoom/panning
2742 param_matrixWorld.map(0,0,&left,&top);
2746 param_matrixWorld.translate(-left,0);
2751 param_matrixWorld.translate(0,-top);
2756 QSize sizeImage = size();
2757 param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom);
2758 if (right < sizeImage.width())
2760 param_matrixWorld.translate(sizeImage.width()-right,0);
2761 right = sizeImage.width();
2763 if (bottom < sizeImage.height())
2765 param_matrixWorld.translate(0,sizeImage.height()-bottom);
2766 bottom = sizeImage.height();
2769 //save corner position
2770 positionCorners.setTopLeft(QPoint(left,top));
2771 positionCorners.setBottomRight(QPoint(right,bottom));
2772 //save also the inv matrix
2773 matrixWorld_inv = param_matrixWorld.inverted();
2775 //viewport()->update();
2778 void DefaultViewPort::moveView(QPointF delta)
2780 param_matrixWorld.translate(delta.x(),delta.y());
2781 controlImagePosition();
2782 viewport()->update();
2785 //factor is -0.5 (zoom out) or 0.5 (zoom in)
2786 void DefaultViewPort::scaleView(qreal factor,QPointF center)
2788 factor/=5;//-0.1 <-> 0.1
2789 factor+=1;//0.9 <-> 1.1
2791 //limit zoom out ---
2792 if (param_matrixWorld.m11()==1 && factor < 1)
2795 if (param_matrixWorld.m11()*factor<1)
2796 factor = 1/param_matrixWorld.m11();
2799 //limit zoom int ---
2800 if (param_matrixWorld.m11()>100 && factor > 1)
2803 //inverse the transform
2805 matrixWorld_inv.map(center.x(),center.y(),&a,&b);
2807 param_matrixWorld.translate(a-factor*a,b-factor*b);
2808 param_matrixWorld.scale(factor,factor);
2810 controlImagePosition();
2813 if (centralWidget->myStatusBar)
2814 centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000);
2816 if (param_matrixWorld.m11()>1)
2817 setCursor(Qt::OpenHandCursor);
2823 //up, down, dclick, move
2824 void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)
2826 Qt::KeyboardModifiers modifiers = evnt->modifiers();
2827 Qt::MouseButtons buttons = evnt->buttons();
2830 if(modifiers & Qt::ShiftModifier)
2831 flags |= CV_EVENT_FLAG_SHIFTKEY;
2832 if(modifiers & Qt::ControlModifier)
2833 flags |= CV_EVENT_FLAG_CTRLKEY;
2834 if(modifiers & Qt::AltModifier)
2835 flags |= CV_EVENT_FLAG_ALTKEY;
2837 if(buttons & Qt::LeftButton)
2838 flags |= CV_EVENT_FLAG_LBUTTON;
2839 if(buttons & Qt::RightButton)
2840 flags |= CV_EVENT_FLAG_RBUTTON;
2841 if(buttons & Qt::MidButton)
2842 flags |= CV_EVENT_FLAG_MBUTTON;
2844 cv_event = CV_EVENT_MOUSEMOVE;
2845 switch(evnt->button())
2847 case Qt::LeftButton:
2848 cv_event = tableMouseButtons[category][0];
2849 flags |= CV_EVENT_FLAG_LBUTTON;
2851 case Qt::RightButton:
2852 cv_event = tableMouseButtons[category][1];
2853 flags |= CV_EVENT_FLAG_RBUTTON;
2856 cv_event = tableMouseButtons[category][2];
2857 flags |= CV_EVENT_FLAG_MBUTTON;
2864 void DefaultViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
2866 //to convert mouse coordinate
2868 matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy);
2870 mouseCoordinate.rx()=floor(pfx/ratioX);
2871 mouseCoordinate.ry()=floor(pfy/ratioY);
2874 on_mouse( cv_event, mouseCoordinate.x(),
2875 mouseCoordinate.y(), flags, on_mouse_param );
2879 QSize DefaultViewPort::sizeHint() const
2882 return QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2884 return QGraphicsView::sizeHint();
2888 void DefaultViewPort::draw2D(QPainter *painter)
2890 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888);
2891 painter->drawImage(QRect(0,0,viewport()->width(),viewport()->height()), image2Draw_qt, QRect(0,0, image2Draw_qt.width(), image2Draw_qt.height()) );
2894 //only if CV_8UC1 or CV_8UC3
2895 void DefaultViewPort::drawStatusBar()
2897 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2900 if (mouseCoordinate.x()>=0 &&
2901 mouseCoordinate.y()>=0 &&
2902 mouseCoordinate.x()<image2Draw_qt.width() &&
2903 mouseCoordinate.y()<image2Draw_qt.height())
2904 // if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0)
2906 QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate);
2908 if (nbChannelOriginImage==CV_8UC3 )
2910 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2911 .arg(mouseCoordinate.x())
2912 .arg(mouseCoordinate.y())+
2913 tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+
2914 tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+
2915 tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2])
2919 if (nbChannelOriginImage==CV_8UC1)
2921 //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed
2922 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2923 .arg(mouseCoordinate.x())
2924 .arg(mouseCoordinate.y())+
2925 tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue))
2931 //accept only CV_8UC1 and CV_8UC8 image for now
2932 void DefaultViewPort::drawImgRegion(QPainter *painter)
2934 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2937 double pixel_width = param_matrixWorld.m11()*ratioX;
2938 double pixel_height = param_matrixWorld.m11()*ratioY;
2940 qreal offsetX = param_matrixWorld.dx()/pixel_width;
2941 offsetX = offsetX - floor(offsetX);
2942 qreal offsetY = param_matrixWorld.dy()/pixel_height;
2943 offsetY = offsetY - floor(offsetY);
2945 QSize view = size();
2946 QVarLengthArray<QLineF, 30> linesX;
2947 for (qreal _x = offsetX*pixel_width; _x < view.width(); _x += pixel_width )
2948 linesX.append(QLineF(_x, 0, _x, view.height()));
2950 QVarLengthArray<QLineF, 30> linesY;
2951 for (qreal _y = offsetY*pixel_height; _y < view.height(); _y += pixel_height )
2952 linesY.append(QLineF(0, _y, view.width(), _y));
2955 QFont f = painter->font();
2956 int original_font_size = f.pointSize();
2958 //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2959 f.setPixelSize(10+(pixel_height-threshold_zoom_img_region)/5);
2960 painter->setFont(f);
2963 for (int j=-1;j<height()/pixel_height;j++)//-1 because display the pixels top rows left columns
2964 for (int i=-1;i<width()/pixel_width;i++)//-1
2966 // Calculate top left of the pixel's position in the viewport (screen space)
2967 QPointF pos_in_view((i+offsetX)*pixel_width, (j+offsetY)*pixel_height);
2969 // Calculate top left of the pixel's position in the image (image space)
2970 QPointF pos_in_image = matrixWorld_inv.map(pos_in_view);// Top left of pixel in view
2971 pos_in_image.rx() = pos_in_image.x()/ratioX;
2972 pos_in_image.ry() = pos_in_image.y()/ratioY;
2973 QPoint point_in_image(pos_in_image.x() + 0.5f,pos_in_image.y() + 0.5f);// Add 0.5 for rounding
2976 if (image2Draw_qt.valid(point_in_image))
2977 rgbValue = image2Draw_qt.pixel(point_in_image);
2979 rgbValue = qRgb(0,0,0);
2981 if (nbChannelOriginImage==CV_8UC3)
2985 val = tr("%1 %2").arg(point2.x()).arg(point2.y());
2986 painter->setPen(QPen(Qt::black, 1));
2987 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
2988 Qt::AlignCenter, val);
2992 val = tr("%1").arg(qRed(rgbValue));
2993 painter->setPen(QPen(Qt::red, 1));
2994 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height/3),
2995 Qt::AlignCenter, val);
2997 val = tr("%1").arg(qGreen(rgbValue));
2998 painter->setPen(QPen(Qt::green, 1));
2999 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+pixel_height/3,pixel_width,pixel_height/3),
3000 Qt::AlignCenter, val);
3002 val = tr("%1").arg(qBlue(rgbValue));
3003 painter->setPen(QPen(Qt::blue, 1));
3004 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+2*pixel_height/3,pixel_width,pixel_height/3),
3005 Qt::AlignCenter, val);
3009 if (nbChannelOriginImage==CV_8UC1)
3011 QString val = tr("%1").arg(qRed(rgbValue));
3012 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height),
3013 Qt::AlignCenter, val);
3017 painter->setPen(QPen(Qt::black, 1));
3018 painter->drawLines(linesX.data(), linesX.size());
3019 painter->drawLines(linesY.data(), linesY.size());
3022 f.setPointSize(original_font_size);
3023 painter->setFont(f);
3027 void DefaultViewPort::drawViewOverview(QPainter *painter)
3029 QSize viewSize = size();
3030 viewSize.scale ( 100, 100,Qt::KeepAspectRatio );
3032 const int margin = 5;
3034 //draw the image's location
3035 painter->setBrush(QColor(0, 0, 0, 127));
3036 painter->setPen(Qt::darkGreen);
3037 painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height()));
3039 //daw the view's location inside the image
3040 qreal ratioSize = 1/param_matrixWorld.m11();
3041 qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height());
3042 painter->setPen(Qt::darkBlue);
3043 painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin,
3044 -positionCorners.top()*ratioSize*ratioWindow,
3045 (viewSize.width()-1)*ratioSize,
3046 (viewSize.height()-1)*ratioSize)
3050 void DefaultViewPort::drawInstructions(QPainter *painter)
3052 QFontMetrics metrics = QFontMetrics(font());
3053 int border = qMax(4, metrics.leading());
3055 QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
3056 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3057 painter->setRenderHint(QPainter::TextAntialiasing);
3058 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3059 QColor(0, 0, 0, 127));
3060 painter->setPen(Qt::white);
3061 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3062 QColor(0, 0, 0, 127));
3064 painter->drawText((width() - qrect.width())/2, border,
3065 qrect.width(), qrect.height(),
3066 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3070 void DefaultViewPort::setSize(QSize /*size_*/)
3075 //////////////////////////////////////////////////////
3078 #ifdef HAVE_QT_OPENGL
3080 OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)
3089 OpenGlViewPort::~OpenGlViewPort()
3093 QWidget* OpenGlViewPort::getWidget()
3098 void OpenGlViewPort::setMouseCallBack(CvMouseCallback callback, void* param)
3100 mouseCallback = callback;
3104 void OpenGlViewPort::writeSettings(QSettings& /*settings*/)
3108 void OpenGlViewPort::readSettings(QSettings& /*settings*/)
3112 double OpenGlViewPort::getRatio()
3114 return (double)width() / height();
3117 void OpenGlViewPort::setRatio(int /*flags*/)
3121 void OpenGlViewPort::updateImage(const CvArr* /*arr*/)
3125 void OpenGlViewPort::startDisplayInfo(QString /*text*/, int /*delayms*/)
3129 void OpenGlViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
3131 glDrawCallback = callback;
3132 glDrawData = userdata;
3135 void OpenGlViewPort::makeCurrentOpenGlContext()
3140 void OpenGlViewPort::updateGl()
3142 QGLWidget::updateGL();
3145 void OpenGlViewPort::initializeGL()
3147 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3150 void OpenGlViewPort::resizeGL(int w, int h)
3152 glViewport(0, 0, w, h);
3155 void OpenGlViewPort::paintGL()
3157 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3160 glDrawCallback(glDrawData);
3163 void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)
3165 int cv_event = -1, flags = 0;
3166 QPoint pt = evnt->pos();
3168 icvmouseHandler(evnt, mouse_down, cv_event, flags);
3169 icvmouseProcessing(QPointF(pt), cv_event, flags);
3171 QGLWidget::mousePressEvent(evnt);
3175 void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)
3177 int cv_event = -1, flags = 0;
3178 QPoint pt = evnt->pos();
3180 icvmouseHandler(evnt, mouse_up, cv_event, flags);
3181 icvmouseProcessing(QPointF(pt), cv_event, flags);
3183 QGLWidget::mouseReleaseEvent(evnt);
3187 void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
3189 int cv_event = -1, flags = 0;
3190 QPoint pt = evnt->pos();
3192 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
3193 icvmouseProcessing(QPointF(pt), cv_event, flags);
3195 QGLWidget::mouseDoubleClickEvent(evnt);
3199 void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)
3201 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
3202 QPoint pt = evnt->pos();
3204 //icvmouseHandler: pass parameters for cv_event, flags
3205 icvmouseHandler(evnt, mouse_move, cv_event, flags);
3206 icvmouseProcessing(QPointF(pt), cv_event, flags);
3208 QGLWidget::mouseMoveEvent(evnt);
3211 void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)
3213 Qt::KeyboardModifiers modifiers = evnt->modifiers();
3214 Qt::MouseButtons buttons = evnt->buttons();
3217 if (modifiers & Qt::ShiftModifier)
3218 flags |= CV_EVENT_FLAG_SHIFTKEY;
3219 if (modifiers & Qt::ControlModifier)
3220 flags |= CV_EVENT_FLAG_CTRLKEY;
3221 if (modifiers & Qt::AltModifier)
3222 flags |= CV_EVENT_FLAG_ALTKEY;
3224 if (buttons & Qt::LeftButton)
3225 flags |= CV_EVENT_FLAG_LBUTTON;
3226 if (buttons & Qt::RightButton)
3227 flags |= CV_EVENT_FLAG_RBUTTON;
3228 if (buttons & Qt::MidButton)
3229 flags |= CV_EVENT_FLAG_MBUTTON;
3231 cv_event = CV_EVENT_MOUSEMOVE;
3232 switch (evnt->button())
3234 case Qt::LeftButton:
3235 cv_event = tableMouseButtons[category][0];
3236 flags |= CV_EVENT_FLAG_LBUTTON;
3239 case Qt::RightButton:
3240 cv_event = tableMouseButtons[category][1];
3241 flags |= CV_EVENT_FLAG_RBUTTON;
3245 cv_event = tableMouseButtons[category][2];
3246 flags |= CV_EVENT_FLAG_MBUTTON;
3255 void OpenGlViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
3258 mouseCallback(cv_event, pt.x(), pt.y(), flags, mouseData);
3262 QSize OpenGlViewPort::sizeHint() const
3264 if (size.width() > 0 && size.height() > 0)
3267 return QGLWidget::sizeHint();
3270 void OpenGlViewPort::setSize(QSize size_)