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 CV_IMPL CvFont cvFontQt(const char* nameFont, int pointSize,CvScalar color,int weight,int style, int spacing)
84 //CvScalar color <- only Qt (blue_component, green_component, red\_component[, alpha_component])
85 int font_face;//<- style in Qt
91 int thickness;//<- weight in Qt
92 float dx;//spacing letter in Qt (0 default) in pixel
93 int line_type;//<- pointSize in Qt
95 CvFont f = {nameFont,color,style,NULL,NULL,NULL,0,0,0,weight,spacing,pointSize};
100 CV_IMPL void cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont* font)
103 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
105 QMetaObject::invokeMethod(guiMainThread,
108 Q_ARG(void*, (void*) img),
109 Q_ARG(QString,QString(text)),
110 Q_ARG(QPoint, QPoint(org.x,org.y)),
111 Q_ARG(void*,(void*) font));
115 double cvGetRatioWindow_QT(const char* name)
118 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
121 QMetaObject::invokeMethod(guiMainThread,
123 //Qt::DirectConnection,
125 Q_RETURN_ARG(double, result),
126 Q_ARG(QString, QString(name)));
132 void cvSetRatioWindow_QT(const char* name,double prop_value)
136 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
138 QMetaObject::invokeMethod(guiMainThread,
141 Q_ARG(QString, QString(name)),
142 Q_ARG(double, prop_value));
146 double cvGetPropWindow_QT(const char* name)
149 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
152 QMetaObject::invokeMethod(guiMainThread,
154 //Qt::DirectConnection,
156 Q_RETURN_ARG(double, result),
157 Q_ARG(QString, QString(name)));
163 void cvSetPropWindow_QT(const char* name,double prop_value)
166 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
168 QMetaObject::invokeMethod(guiMainThread,
171 Q_ARG(QString, QString(name)),
172 Q_ARG(double, prop_value));
176 void cvSetModeWindow_QT(const char* name, double prop_value)
179 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
181 QMetaObject::invokeMethod(guiMainThread,
184 Q_ARG(QString, QString(name)),
185 Q_ARG(double, prop_value));
189 double cvGetModeWindow_QT(const char* name)
192 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
196 QMetaObject::invokeMethod(guiMainThread,
199 Q_RETURN_ARG(double, result),
200 Q_ARG(QString, QString(name)));
206 CV_IMPL void cvDisplayOverlay(const char* name, const char* text, int delayms)
209 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
211 QMetaObject::invokeMethod(guiMainThread,
214 //Qt::DirectConnection,
215 Q_ARG(QString, QString(name)),
216 Q_ARG(QString, QString(text)),
217 Q_ARG(int, delayms));
221 CV_IMPL void cvSaveWindowParameters(const char* name)
224 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
226 QMetaObject::invokeMethod(guiMainThread,
227 "saveWindowParameters",
229 Q_ARG(QString, QString(name)));
233 CV_IMPL void cvLoadWindowParameters(const char* name)
236 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
238 QMetaObject::invokeMethod(guiMainThread,
239 "loadWindowParameters",
241 Q_ARG(QString, QString(name)));
245 CV_IMPL void cvDisplayStatusBar(const char* name, const char* text, int delayms)
248 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
250 QMetaObject::invokeMethod(guiMainThread,
253 //Qt::DirectConnection,
254 Q_ARG(QString, QString(name)),
255 Q_ARG(QString, QString(text)),
256 Q_ARG(int, delayms));
260 CV_IMPL int cvWaitKey(int delay)
267 unsigned long delayms = delay <= 0 ? ULONG_MAX : delay; //in milliseconds
272 if (key_pressed.wait(&mutexKey, delayms)) //false if timeout
281 //cannot use wait here because events will not be distributed before processEvents (the main eventLoop is broken)
282 //so I create a Thread for the QTimer
285 guiMainThread->timer->start(delay);
289 while (!guiMainThread->bTimeOut)
291 qApp->processEvents(QEventLoop::AllEvents);
293 if (!guiMainThread)//when all the windows are deleted
301 guiMainThread->timer->stop();
302 //printf("keypressed\n");
313 * //will not work, I broke the event loop !!!!
315 QWaitCondition waitCondition;
316 waitCondition.wait(&dummy, 2);
319 //to decrease CPU usage
320 //sleep 1 millisecond
321 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
329 guiMainThread->bTimeOut = false;
337 //This function is experimental and some functions (such as cvSet/getWindowProperty will not work)
338 //We recommend not using this function for now
339 CV_IMPL int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[])
342 QFuture<int> future = QtConcurrent::run(pt2Func, argc, argv);
343 return guiMainThread->start();
347 CV_IMPL void cvStopLoop()
353 static CvWindow* icvFindWindowByName(QString name)
355 CvWindow* window = 0;
357 //This is not a very clean way to do the stuff. Indeed, QAction automatically generate toolTil (QLabel)
358 //that can be grabbed here and crash the code at 'w->param_name==name'.
359 foreach (QWidget* widget, QApplication::topLevelWidgets())
361 if (widget->isWindow() && !widget->parentWidget())//is a window without parent
363 CvWinModel* temp = (CvWinModel*) widget;
365 if (temp->type == type_CvWindow)
367 CvWindow* w = (CvWindow*) temp;
368 if (w->windowTitle() == name)
381 static CvBar* icvFindBarByName(QBoxLayout* layout, QString name_bar, typeBar type)
386 int stop_index = layout->layout()->count();
388 for (int i = 0; i < stop_index; ++i)
390 CvBar* t = (CvBar*) layout->layout()->itemAt(i);
392 if (t->type == type && t->name_bar == name_bar)
400 static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char* name_window, QBoxLayout* layout = NULL)
402 QString nameQt(name_trackbar);
404 if (!name_window && global_control_panel) //window name is null and we have a control panel
405 layout = global_control_panel->myLayout;
409 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(name_window));
412 CV_Error(CV_StsNullPtr, "NULL window handler");
414 if (w->param_gui_mode == CV_GUI_NORMAL)
415 return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
417 if (w->param_gui_mode == CV_GUI_EXPANDED)
419 CvBar* result = icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
422 return (CvTrackbar*) result;
424 return (CvTrackbar*) icvFindBarByName(global_control_panel->myLayout, nameQt, type_CvTrackbar);
431 //layout was specified
432 return (CvTrackbar*) icvFindBarByName(layout, nameQt, type_CvTrackbar);
437 static CvButtonbar* icvFindButtonBarByName(const char* button_name, QBoxLayout* layout)
439 QString nameQt(button_name);
440 return (CvButtonbar*) icvFindBarByName(layout, nameQt, type_CvButtonbar);
444 static int icvInitSystem(int* c, char** v)
446 //"For any GUI application using Qt, there is precisely one QApplication object"
447 if (!QApplication::instance())
449 new QApplication(*c, v);
451 qDebug() << "init done";
453 #ifdef HAVE_QT_OPENGL
454 qDebug() << "opengl support available";
462 CV_IMPL int cvInitSystem(int, char**)
464 icvInitSystem(¶meterSystemC, parameterSystemV);
469 CV_IMPL int cvNamedWindow(const char* name, int flags)
472 guiMainThread = new GuiReceiver;
475 QMetaObject::invokeMethod(guiMainThread,
477 Qt::BlockingQueuedConnection,
478 Q_ARG(QString, QString(name)),
481 guiMainThread->createWindow(QString(name), flags);
483 return 1; //Dummy value
487 CV_IMPL void cvDestroyWindow(const char* name)
490 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
492 QMetaObject::invokeMethod(guiMainThread,
494 //Qt::BlockingQueuedConnection,
496 Q_ARG(QString, QString(name)));
500 CV_IMPL void cvDestroyAllWindows()
505 QMetaObject::invokeMethod(guiMainThread,
507 //Qt::BlockingQueuedConnection,
512 CV_IMPL void* cvGetWindowHandle(const char* name)
515 CV_Error( CV_StsNullPtr, "NULL name string" );
517 return (void*) icvFindWindowByName(QLatin1String(name));
521 CV_IMPL const char* cvGetWindowName(void* window_handle)
524 CV_Error( CV_StsNullPtr, "NULL window handler" );
526 return ((CvWindow*)window_handle)->windowTitle().toLatin1().data();
530 CV_IMPL void cvMoveWindow(const char* name, int x, int y)
533 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
535 QMetaObject::invokeMethod(guiMainThread,
537 //Qt::BlockingQueuedConnection,
539 Q_ARG(QString, QString(name)),
545 CV_IMPL void cvResizeWindow(const char* name, int width, int height)
548 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
550 QMetaObject::invokeMethod(guiMainThread,
552 //Qt::BlockingQueuedConnection,
554 Q_ARG(QString, QString(name)),
560 CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata)
563 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
565 QMetaObject::invokeMethod(guiMainThread,
568 Q_ARG(QString, QString(name_bar)),
569 Q_ARG(QString, QString(window_name)),
570 Q_ARG(void*, (void*)val),
572 Q_ARG(void*, (void*)on_notify),
573 Q_ARG(void*, (void*)userdata));
575 return 1; //dummy value
579 CV_IMPL int cvStartWindowThread()
585 CV_IMPL int cvCreateTrackbar(const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change)
588 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
590 QMetaObject::invokeMethod(guiMainThread,
593 Q_ARG(QString, QString(name_bar)),
594 Q_ARG(QString, QString(window_name)),
595 Q_ARG(void*, (void*)value),
597 Q_ARG(void*, (void*)on_change));
599 return 1; //dummy value
603 CV_IMPL int cvCreateButton(const char* button_name, CvButtonCallback on_change, void* userdata, int button_type, int initial_button_state)
606 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
608 if (initial_button_state < 0 || initial_button_state > 1)
611 QMetaObject::invokeMethod(guiMainThread,
614 Q_ARG(QString, QString(button_name)),
615 Q_ARG(int, button_type),
616 Q_ARG(int, initial_button_state),
617 Q_ARG(void*, (void*)on_change),
618 Q_ARG(void*, userdata));
620 return 1;//dummy value
624 CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name)
628 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
631 result = t->slider->value();
637 CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int pos)
639 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
642 t->slider->setValue(pos);
646 /* assign callback for mouse events */
647 CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param)
649 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
652 CV_Error(CV_StsNullPtr, "NULL window handler");
654 w->setMouseCallBack(on_mouse, param);
659 CV_IMPL void cvShowImage(const char* name, const CvArr* arr)
662 guiMainThread = new GuiReceiver;
664 QMetaObject::invokeMethod(guiMainThread,
666 //Qt::BlockingQueuedConnection,
667 Qt::DirectConnection,
668 Q_ARG(QString, QString(name)),
669 Q_ARG(void*, (void*)arr));
673 #ifdef HAVE_QT_OPENGL
675 CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
678 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
680 QMetaObject::invokeMethod(guiMainThread,
681 "setOpenGlDrawCallback",
683 Q_ARG(QString, QString(window_name)),
684 Q_ARG(void*, (void*)callback),
685 Q_ARG(void*, userdata));
689 CV_IMPL void cvSetOpenGlContext(const char* window_name)
692 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
694 QMetaObject::invokeMethod(guiMainThread,
697 Q_ARG(QString, QString(window_name)));
701 CV_IMPL void cvUpdateWindow(const char* window_name)
704 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
706 QMetaObject::invokeMethod(guiMainThread,
709 Q_ARG(QString, QString(window_name)));
715 double cvGetOpenGlProp_QT(const char* name)
721 QMetaObject::invokeMethod(guiMainThread,
724 Q_RETURN_ARG(double, result),
725 Q_ARG(QString, QString(name)));
732 //////////////////////////////////////////////////////
736 GuiReceiver::GuiReceiver() : bTimeOut(false), nb_windows(0)
738 doesExternalQAppExist = (QApplication::instance() != 0);
739 icvInitSystem(¶meterSystemC, parameterSystemV);
741 timer = new QTimer(this);
742 QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
743 timer->setSingleShot(true);
747 void GuiReceiver::isLastWindow()
749 if (--nb_windows <= 0)
751 delete guiMainThread;//delete global_control_panel too
752 guiMainThread = NULL;
754 if (!doesExternalQAppExist)
762 GuiReceiver::~GuiReceiver()
764 if (global_control_panel)
766 delete global_control_panel;
767 global_control_panel = NULL;
772 void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2)
777 mat = cvGetMat(arr, &stub);
779 int nbChannelOriginImage = cvGetElemType(mat);
780 if (nbChannelOriginImage != CV_8UC3) return; //for now, font works only with 8UC3
782 QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888);
784 CvFont* font = (CvFont*)arg2;
789 QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/);
790 f.setStyle((QFont::Style) font->font_face/*style*/);
791 f.setLetterSpacing(QFont::AbsoluteSpacing, font->dx/*spacing*/);
792 //cvScalar(blue_component, green_component, red_component[, alpha_component])
793 //Qt map non-transparent to 0xFF and transparent to 0
794 //OpenCV scalar is the reverse, so 255-font->color.val[3]
795 qp.setPen(QColor(font->color.val[2], font->color.val[1], font->color.val[0], 255 - font->color.val[3]));
798 qp.drawText(org, text);
803 void GuiReceiver::saveWindowParameters(QString name)
805 QPointer<CvWindow> w = icvFindWindowByName(name);
812 void GuiReceiver::loadWindowParameters(QString name)
814 QPointer<CvWindow> w = icvFindWindowByName(name);
821 double GuiReceiver::getRatioWindow(QString name)
823 QPointer<CvWindow> w = icvFindWindowByName(name);
828 return w->getRatio();
832 void GuiReceiver::setRatioWindow(QString name, double arg2)
834 QPointer<CvWindow> w = icvFindWindowByName( name.toLatin1().data() );
839 int flags = (int) arg2;
845 double GuiReceiver::getPropWindow(QString name)
847 QPointer<CvWindow> w = icvFindWindowByName(name);
852 return (double) w->getPropWindow();
856 void GuiReceiver::setPropWindow(QString name, double arg2)
858 QPointer<CvWindow> w = icvFindWindowByName(name);
863 int flags = (int) arg2;
865 w->setPropWindow(flags);
869 double GuiReceiver::isFullScreen(QString name)
871 QPointer<CvWindow> w = icvFindWindowByName(name);
876 return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL;
880 void GuiReceiver::toggleFullScreen(QString name, double arg2)
882 QPointer<CvWindow> w = icvFindWindowByName(name);
887 int flags = (int) arg2;
889 w->toggleFullScreen(flags);
893 void GuiReceiver::createWindow(QString name, int flags)
896 CV_Error(CV_StsNullPtr, "NULL session handler" );
898 // Check the name in the storage
899 if (icvFindWindowByName(name.toLatin1().data()))
905 new CvWindow(name, flags);
909 void GuiReceiver::timeOut()
915 void GuiReceiver::displayInfo(QString name, QString text, int delayms)
917 QPointer<CvWindow> w = icvFindWindowByName(name);
920 w->displayInfo(text, delayms);
924 void GuiReceiver::displayStatusBar(QString name, QString text, int delayms)
926 QPointer<CvWindow> w = icvFindWindowByName(name);
929 w->displayStatusBar(text, delayms);
933 void GuiReceiver::showImage(QString name, void* arr)
935 QPointer<CvWindow> w = icvFindWindowByName(name);
937 if (!w) //as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null
939 cvNamedWindow(name.toLatin1().data());
940 w = icvFindWindowByName(name);
944 return; // keep silence here.
950 mat = cvGetMat(arr, &stub);
952 cv::Mat im = cv::cvarrToMat(mat);
953 cv::imshow(name.toUtf8().data(), im);
965 void GuiReceiver::destroyWindow(QString name)
967 QPointer<CvWindow> w = icvFindWindowByName(name);
973 //in not-multiThreads mode, looks like the window is hidden but not deleted
974 //so I do it manually
975 //otherwise QApplication do it for me if the exec command was executed (in multiThread mode)
982 void GuiReceiver::destroyAllWindow()
985 CV_Error(CV_StsNullPtr, "NULL session handler" );
989 // WARNING: this could even close windows from an external parent app
990 //#TODO check externalQAppExists and in case it does, close windows carefully,
991 // i.e. apply the className-check from below...
992 qApp->closeAllWindows();
996 bool isWidgetDeleted = true;
997 while(isWidgetDeleted)
999 isWidgetDeleted = false;
1000 QWidgetList list = QApplication::topLevelWidgets();
1001 for (int i = 0; i < list.count(); i++)
1003 QObject *obj = list.at(i);
1004 if (obj->metaObject()->className() == QString("CvWindow"))
1007 isWidgetDeleted = true;
1016 void GuiReceiver::moveWindow(QString name, int x, int y)
1018 QPointer<CvWindow> w = icvFindWindowByName(name);
1025 void GuiReceiver::resizeWindow(QString name, int width, int height)
1027 QPointer<CvWindow> w = icvFindWindowByName(name);
1032 w->setViewportSize(QSize(width, height));
1037 void GuiReceiver::enablePropertiesButtonEachWindow()
1039 //For each window, enable window property button
1040 foreach (QWidget* widget, QApplication::topLevelWidgets())
1042 if (widget->isWindow() && !widget->parentWidget()) //is a window without parent
1044 CvWinModel* temp = (CvWinModel*) widget;
1045 if (temp->type == type_CvWindow)
1047 CvWindow* w = (CvWindow*) widget;
1049 //active window properties button
1050 w->enablePropertiesButton();
1057 void GuiReceiver::addButton(QString button_name, int button_type, int initial_button_state, void* on_change, void* userdata)
1059 if (!global_control_panel)
1062 QPointer<CvButtonbar> b;
1064 if (global_control_panel->myLayout->count() == 0) //if that is the first button attach to the control panel, create a new button bar
1066 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1067 enablePropertiesButtonEachWindow();
1072 CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count() - 1);
1074 if (lastbar->type == type_CvTrackbar) //if last bar is a trackbar, create a new buttonbar, else, attach to the current bar
1075 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1077 b = (CvButtonbar*) lastbar;
1081 b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state);
1085 void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata)
1087 QBoxLayout *layout = NULL;
1088 QPointer<CvWindow> w;
1090 if (!window_name.isEmpty())
1092 w = icvFindWindowByName(window_name);
1099 if (global_control_panel)
1100 layout = global_control_panel->myLayout;
1103 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1105 if (t) //trackbar exists
1109 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1111 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1112 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1114 CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
1118 void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change)
1120 QBoxLayout *layout = NULL;
1121 QPointer<CvWindow> w;
1123 if (!window_name.isEmpty())
1125 w = icvFindWindowByName(window_name);
1132 if (global_control_panel)
1133 layout = global_control_panel->myLayout;
1136 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1138 if (t) //trackbar exists
1142 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1144 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1145 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1147 CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
1151 int GuiReceiver::start()
1153 return qApp->exec();
1157 void GuiReceiver::setOpenGlDrawCallback(QString name, void* callback, void* userdata)
1159 QPointer<CvWindow> w = icvFindWindowByName(name);
1162 w->setOpenGlDrawCallback((CvOpenGlDrawCallback) callback, userdata);
1165 void GuiReceiver::setOpenGlContext(QString name)
1167 QPointer<CvWindow> w = icvFindWindowByName(name);
1170 w->makeCurrentOpenGlContext();
1173 void GuiReceiver::updateWindow(QString name)
1175 QPointer<CvWindow> w = icvFindWindowByName(name);
1181 double GuiReceiver::isOpenGl(QString name)
1185 QPointer<CvWindow> w = icvFindWindowByName(name);
1188 result = (double) w->isOpenGl();
1194 //////////////////////////////////////////////////////
1198 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)
1201 callback2 = on_change;
1204 create(arg, name, value, _count);
1208 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)
1210 callback = on_change;
1214 create(arg, name, value, _count);
1218 void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)
1220 type = type_CvTrackbar;
1223 setObjectName(name_bar);
1226 slider = new QSlider(Qt::Horizontal);
1227 slider->setFocusPolicy(Qt::StrongFocus);
1228 slider->setMinimum(0);
1229 slider->setMaximum(_count);
1230 slider->setPageStep(5);
1231 slider->setValue(*value);
1232 slider->setTickPosition(QSlider::TicksBelow);
1235 //Change style of the Slider
1236 //slider->setStyleSheet(str_Trackbar_css);
1238 QFile qss(":/stylesheet-trackbar");
1239 if (qss.open(QFile::ReadOnly))
1241 slider->setStyleSheet(QLatin1String(qss.readAll()));
1246 //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?)
1247 //slider->setTickPosition(QSlider::TicksBelow);
1248 label = new QPushButton;
1249 label->setFlat(true);
1250 setLabel(slider->value());
1253 QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(update(int)));
1255 QObject::connect(label, SIGNAL(clicked()), this, SLOT(createDialog()));
1257 //label->setStyleSheet("QPushButton:disabled {color: black}");
1259 addWidget(label, Qt::AlignLeft);//name + value
1260 addWidget(slider, Qt::AlignCenter);//slider
1264 void CvTrackbar::createDialog()
1268 //crash if I access the values directly and give them to QInputDialog, so do a copy first.
1269 int value = slider->value();
1270 int step = slider->singleStep();
1271 int min = slider->minimum();
1272 int max = slider->maximum();
1275 #if QT_VERSION >= 0x040500
1276 QInputDialog::getInt
1278 QInputDialog::getInteger
1280 (this->parentWidget(),
1281 tr("Slider %1").arg(name_bar),
1290 slider->setValue(i);
1294 void CvTrackbar::update(int myvalue)
1298 *dataSlider = myvalue;
1307 callback2(myvalue, userdata);
1313 void CvTrackbar::setLabel(int myvalue)
1315 QString nameNormalized = name_bar.leftJustified( 10, ' ', true );
1316 QString valueMaximum = QString("%1").arg(slider->maximum());
1317 QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum);
1318 label->setText(str);
1322 //////////////////////////////////////////////////////
1326 //here CvButtonbar class
1327 CvButtonbar::CvButtonbar(QWidget* arg, QString arg2)
1329 type = type_CvButtonbar;
1332 setObjectName(name_bar);
1334 group_button = new QButtonGroup(this);
1338 void CvButtonbar::setLabel()
1340 QString nameNormalized = name_bar.leftJustified(10, ' ', true);
1341 label->setText(nameNormalized);
1345 void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state)
1347 QString button_name = name;
1349 if (button_name == "")
1350 button_name = tr("button %1").arg(this->count());
1352 QPointer<QAbstractButton> button;
1354 if (button_type == CV_PUSH_BUTTON)
1355 button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata);
1357 if (button_type == CV_CHECKBOX)
1358 button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state);
1360 if (button_type == CV_RADIOBOX)
1362 button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state);
1363 group_button->addButton(button);
1368 if (button_type == CV_PUSH_BUTTON)
1369 QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool)));
1371 QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool)));
1373 addWidget(button, Qt::AlignCenter);
1378 //////////////////////////////////////////////////////
1383 CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4)
1390 setObjectName(button_name);
1391 setText(button_name);
1398 void CvPushButton::callCallBack(bool checked)
1401 callback(checked, userdata);
1405 CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1412 setObjectName(button_name);
1413 setCheckState((initial_button_state == 1 ? Qt::Checked : Qt::Unchecked));
1414 setText(button_name);
1421 void CvCheckBox::callCallBack(bool checked)
1424 callback(checked, userdata);
1428 CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1435 setObjectName(button_name);
1436 setChecked(initial_button_state);
1437 setText(button_name);
1443 void CvRadioButton::callCallBack(bool checked)
1446 callback(checked, userdata);
1450 //////////////////////////////////////////////////////
1454 //here CvWinProperties class
1455 CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)
1457 //setParent(parent);
1458 type = type_CvWinProperties;
1459 setWindowFlags(Qt::Tool);
1460 setContentsMargins(0, 0, 0, 0);
1461 setWindowTitle(name_paraWindow);
1462 setObjectName(name_paraWindow);
1465 myLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1466 myLayout->setObjectName(QString::fromUtf8("boxLayout"));
1467 myLayout->setContentsMargins(0, 0, 0, 0);
1468 myLayout->setSpacing(0);
1469 myLayout->setMargin(0);
1470 myLayout->setSizeConstraint(QLayout::SetFixedSize);
1471 setLayout(myLayout);
1477 void CvWinProperties::closeEvent(QCloseEvent* e)
1479 e->accept(); //intersept the close event (not sure I really need it)
1480 //an hide event is also sent. I will intercept it and do some processing
1484 void CvWinProperties::showEvent(QShowEvent* evnt)
1486 //why -1,-1 ?: do this trick because the first time the code is run,
1487 //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).
1488 //then hide will save the last position and thus, we want to retreive it (event accepted).
1489 QPoint mypos(-1, -1);
1490 QSettings settings("OpenCV2", windowTitle());
1491 mypos = settings.value("pos", mypos).toPoint();
1505 void CvWinProperties::hideEvent(QHideEvent* evnt)
1507 QSettings settings("OpenCV2", windowTitle());
1508 settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)
1513 CvWinProperties::~CvWinProperties()
1515 //clear the setting pos
1516 QSettings settings("OpenCV2", windowTitle());
1517 settings.remove("pos");
1521 //////////////////////////////////////////////////////
1525 CvWindow::CvWindow(QString name, int arg2)
1527 type = type_CvWindow;
1528 moveToThread(qApp->instance()->thread());
1530 param_flags = arg2 & 0x0000000F;
1531 param_gui_mode = arg2 & 0x000000F0;
1532 param_ratio_mode = arg2 & 0x00000F00;
1534 //setAttribute(Qt::WA_DeleteOnClose); //in other case, does not release memory
1535 setContentsMargins(0, 0, 0, 0);
1536 setWindowTitle(name);
1537 setObjectName(name);
1539 setFocus( Qt::PopupFocusReason ); //#1695 arrow keys are not received without the explicit focus
1542 setMinimumSize(1, 1);
1544 //1: create control panel
1545 if (!global_control_panel)
1546 global_control_panel = createParameterWindow();
1550 createGlobalLayout();
1553 #ifndef HAVE_QT_OPENGL
1554 if (arg2 & CV_WINDOW_OPENGL)
1555 CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
1556 mode_display = CV_MODE_NORMAL;
1558 mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
1559 if (mode_display == CV_MODE_OPENGL)
1560 param_gui_mode = CV_GUI_NORMAL;
1564 //4: shortcuts and actions
1565 //5: toolBar and statusbar
1566 if (param_gui_mode == CV_GUI_EXPANDED)
1575 //Now attach everything
1577 myGlobalLayout->addWidget(myToolBar, Qt::AlignCenter);
1579 myGlobalLayout->addWidget(myView->getWidget(), Qt::AlignCenter);
1581 myGlobalLayout->addLayout(myBarLayout, Qt::AlignCenter);
1584 myGlobalLayout->addWidget(myStatusBar, Qt::AlignCenter);
1586 setLayout(myGlobalLayout);
1591 CvWindow::~CvWindow()
1594 guiMainThread->isLastWindow();
1598 void CvWindow::setMouseCallBack(CvMouseCallback callback, void* param)
1600 myView->setMouseCallBack(callback, param);
1604 void CvWindow::writeSettings()
1606 //organisation and application's name
1607 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1609 settings.setValue("pos", pos());
1610 settings.setValue("size", size());
1611 settings.setValue("mode_resize" ,param_flags);
1612 settings.setValue("mode_gui", param_gui_mode);
1614 myView->writeSettings(settings);
1616 icvSaveTrackbars(&settings);
1618 if (global_control_panel)
1620 icvSaveControlPanel();
1621 settings.setValue("posPanel", global_control_panel->pos());
1627 //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars)
1628 void CvWindow::readSettings()
1630 //organisation and application's name
1631 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1633 QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();
1634 QSize _size = settings.value("size", QSize(400, 400)).toSize();
1636 param_flags = settings.value("mode_resize", param_flags).toInt();
1637 param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();
1639 param_flags = settings.value("mode_resize", param_flags).toInt();
1641 myView->readSettings(settings);
1644 icvLoadTrackbars(&settings);
1649 if (global_control_panel)
1651 icvLoadControlPanel();
1652 global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint());
1657 double CvWindow::getRatio()
1659 return myView->getRatio();
1663 void CvWindow::setRatio(int flags)
1665 myView->setRatio(flags);
1669 int CvWindow::getPropWindow()
1675 void CvWindow::setPropWindow(int flags)
1677 if (param_flags == flags) //nothing to do
1682 case CV_WINDOW_NORMAL:
1683 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1684 param_flags = flags;
1688 case CV_WINDOW_AUTOSIZE:
1689 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1690 param_flags = flags;
1700 void CvWindow::toggleFullScreen(int flags)
1702 if (isFullScreen() && flags == CV_WINDOW_NORMAL)
1709 if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN)
1718 void CvWindow::updateImage(void* arr)
1720 myView->updateImage(arr);
1724 void CvWindow::displayInfo(QString text, int delayms)
1726 myView->startDisplayInfo(text, delayms);
1730 void CvWindow::displayStatusBar(QString text, int delayms)
1733 myStatusBar->showMessage(text, delayms);
1737 void CvWindow::enablePropertiesButton()
1739 if (!vect_QActions.empty())
1740 vect_QActions[9]->setDisabled(false);
1744 CvButtonbar* CvWindow::createButtonBar(QString name_bar)
1746 QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel, name_bar);
1747 t->setAlignment(Qt::AlignHCenter);
1749 QPointer<QBoxLayout> myLayout = global_control_panel->myLayout;
1751 myLayout->insertLayout(myLayout->count(), t);
1757 void CvWindow::addSlider(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback on_change)
1759 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change);
1760 t->setAlignment(Qt::AlignHCenter);
1762 QPointer<QBoxLayout> myLayout;
1766 myLayout = w->myBarLayout;
1770 myLayout = global_control_panel->myLayout;
1772 //if first one, enable control panel
1773 if (myLayout->count() == 0)
1774 guiMainThread->enablePropertiesButtonEachWindow();
1777 myLayout->insertLayout(myLayout->count(), t);
1781 void CvWindow::addSlider2(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata)
1783 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change, userdata);
1784 t->setAlignment(Qt::AlignHCenter);
1786 QPointer<QBoxLayout> myLayout;
1790 myLayout = w->myBarLayout;
1794 myLayout = global_control_panel->myLayout;
1796 //if first one, enable control panel
1797 if (myLayout->count() == 0)
1798 guiMainThread->enablePropertiesButtonEachWindow();
1801 myLayout->insertLayout(myLayout->count(), t);
1805 void CvWindow::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
1807 myView->setOpenGlDrawCallback(callback, userdata);
1811 void CvWindow::makeCurrentOpenGlContext()
1813 myView->makeCurrentOpenGlContext();
1817 void CvWindow::updateGl()
1823 bool CvWindow::isOpenGl()
1825 return mode_display == CV_MODE_OPENGL;
1829 void CvWindow::setViewportSize(QSize _size)
1831 myView->getWidget()->resize(_size);
1832 myView->setSize(_size);
1836 void CvWindow::createBarLayout()
1838 myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1839 myBarLayout->setObjectName(QString::fromUtf8("barLayout"));
1840 myBarLayout->setContentsMargins(0, 0, 0, 0);
1841 myBarLayout->setSpacing(0);
1842 myBarLayout->setMargin(0);
1846 void CvWindow::createGlobalLayout()
1848 myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1849 myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout"));
1850 myGlobalLayout->setContentsMargins(0, 0, 0, 0);
1851 myGlobalLayout->setSpacing(0);
1852 myGlobalLayout->setMargin(0);
1853 setMinimumSize(1, 1);
1855 if (param_flags == CV_WINDOW_AUTOSIZE)
1856 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1857 else if (param_flags == CV_WINDOW_NORMAL)
1858 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1862 void CvWindow::createView()
1864 #ifdef HAVE_QT_OPENGL
1866 myView = new OpenGlViewPort(this);
1869 myView = new DefaultViewPort(this, param_ratio_mode);
1873 void CvWindow::createActions()
1875 vect_QActions.resize(10);
1877 QWidget* view = myView->getWidget();
1879 //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually
1880 vect_QActions[0] = new QAction(QIcon(":/left-icon"), "Panning left (CTRL+arrowLEFT)", this);
1881 vect_QActions[0]->setIconVisibleInMenu(true);
1882 QObject::connect(vect_QActions[0], SIGNAL(triggered()), view, SLOT(siftWindowOnLeft()));
1884 vect_QActions[1] = new QAction(QIcon(":/right-icon"), "Panning right (CTRL+arrowRIGHT)", this);
1885 vect_QActions[1]->setIconVisibleInMenu(true);
1886 QObject::connect(vect_QActions[1], SIGNAL(triggered()), view, SLOT(siftWindowOnRight()));
1888 vect_QActions[2] = new QAction(QIcon(":/up-icon"), "Panning up (CTRL+arrowUP)", this);
1889 vect_QActions[2]->setIconVisibleInMenu(true);
1890 QObject::connect(vect_QActions[2], SIGNAL(triggered()), view, SLOT(siftWindowOnUp()));
1892 vect_QActions[3] = new QAction(QIcon(":/down-icon"), "Panning down (CTRL+arrowDOWN)", this);
1893 vect_QActions[3]->setIconVisibleInMenu(true);
1894 QObject::connect(vect_QActions[3], SIGNAL(triggered()), view, SLOT(siftWindowOnDown()) );
1896 vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"), "Zoom x1 (CTRL+P)", this);
1897 vect_QActions[4]->setIconVisibleInMenu(true);
1898 QObject::connect(vect_QActions[4], SIGNAL(triggered()), view, SLOT(resetZoom()));
1900 vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"), tr("Zoom x%1 (see label) (CTRL+X)").arg(threshold_zoom_img_region), this);
1901 vect_QActions[5]->setIconVisibleInMenu(true);
1902 QObject::connect(vect_QActions[5], SIGNAL(triggered()), view, SLOT(imgRegion()));
1904 vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"), "Zoom in (CTRL++)", this);
1905 vect_QActions[6]->setIconVisibleInMenu(true);
1906 QObject::connect(vect_QActions[6], SIGNAL(triggered()), view, SLOT(ZoomIn()));
1908 vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"), "Zoom out (CTRL+-)", this);
1909 vect_QActions[7]->setIconVisibleInMenu(true);
1910 QObject::connect(vect_QActions[7], SIGNAL(triggered()), view, SLOT(ZoomOut()));
1912 vect_QActions[8] = new QAction(QIcon(":/save-icon"), "Save current image (CTRL+S)", this);
1913 vect_QActions[8]->setIconVisibleInMenu(true);
1914 QObject::connect(vect_QActions[8], SIGNAL(triggered()), view, SLOT(saveView()));
1916 vect_QActions[9] = new QAction(QIcon(":/properties-icon"), "Display properties window (CTRL+P)", this);
1917 vect_QActions[9]->setIconVisibleInMenu(true);
1918 QObject::connect(vect_QActions[9], SIGNAL(triggered()), this, SLOT(displayPropertiesWin()));
1920 if (global_control_panel->myLayout->count() == 0)
1921 vect_QActions[9]->setDisabled(true);
1925 void CvWindow::createShortcuts()
1927 vect_QShortcuts.resize(10);
1929 QWidget* view = myView->getWidget();
1931 vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this);
1932 QObject::connect(vect_QShortcuts[0], SIGNAL(activated()), view, SLOT(siftWindowOnLeft()));
1934 vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this);
1935 QObject::connect(vect_QShortcuts[1], SIGNAL(activated()), view, SLOT(siftWindowOnRight()));
1937 vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this);
1938 QObject::connect(vect_QShortcuts[2], SIGNAL(activated()), view, SLOT(siftWindowOnUp()));
1940 vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this);
1941 QObject::connect(vect_QShortcuts[3], SIGNAL(activated()), view, SLOT(siftWindowOnDown()));
1943 vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this);
1944 QObject::connect(vect_QShortcuts[4], SIGNAL(activated()), view, SLOT(resetZoom()));
1946 vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this);
1947 QObject::connect(vect_QShortcuts[5], SIGNAL(activated()), view, SLOT(imgRegion()));
1949 vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this);
1950 QObject::connect(vect_QShortcuts[6], SIGNAL(activated()), view, SLOT(ZoomIn()));
1952 vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this);
1953 QObject::connect(vect_QShortcuts[7], SIGNAL(activated()), view, SLOT(ZoomOut()));
1955 vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this);
1956 QObject::connect(vect_QShortcuts[8], SIGNAL(activated()), view, SLOT(saveView()));
1958 vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this);
1959 QObject::connect(vect_QShortcuts[9], SIGNAL(activated()), this, SLOT(displayPropertiesWin()));
1963 void CvWindow::createToolBar()
1965 myToolBar = new QToolBar(this);
1966 myToolBar->setFloatable(false); //is not a window
1967 myToolBar->setFixedHeight(28);
1968 myToolBar->setMinimumWidth(1);
1970 foreach (QAction *a, vect_QActions)
1971 myToolBar->addAction(a);
1975 void CvWindow::createStatusBar()
1977 myStatusBar = new QStatusBar(this);
1978 myStatusBar->setSizeGripEnabled(false);
1979 myStatusBar->setFixedHeight(20);
1980 myStatusBar->setMinimumWidth(1);
1981 myStatusBar_msg = new QLabel;
1983 //I comment this because if we change the style, myview (the picture)
1984 //will not be the correct size anymore (will lost 2 pixel because of the borders)
1986 //myStatusBar_msg->setFrameStyle(QFrame::Raised);
1988 myStatusBar_msg->setAlignment(Qt::AlignHCenter);
1989 myStatusBar->addWidget(myStatusBar_msg);
1993 void CvWindow::hideTools()
1999 myStatusBar->hide();
2001 if (global_control_panel)
2002 global_control_panel->hide();
2006 void CvWindow::showTools()
2012 myStatusBar->show();
2016 CvWinProperties* CvWindow::createParameterWindow()
2018 QString name_paraWindow = QFileInfo(QApplication::applicationFilePath()).fileName() + " settings";
2020 CvWinProperties* result = new CvWinProperties(name_paraWindow, guiMainThread);
2026 void CvWindow::displayPropertiesWin()
2028 if (global_control_panel->isHidden())
2029 global_control_panel->show();
2031 global_control_panel->hide();
2035 //Need more test here !
2036 void CvWindow::keyPressEvent(QKeyEvent *evnt)
2038 //see http://doc.trolltech.com/4.6/qt.html#Key-enum
2039 int key = evnt->key();
2041 Qt::Key qtkey = static_cast<Qt::Key>(key);
2042 char asciiCode = QTest::keyToAscii(qtkey);
2044 key = static_cast<int>(asciiCode);
2046 key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend
2048 //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions
2049 if (evnt->modifiers() != Qt::ControlModifier)
2054 key_pressed.wakeAll();
2058 QWidget::keyPressEvent(evnt);
2062 void CvWindow::icvLoadControlPanel()
2064 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");
2066 int bsize = settings.beginReadArray("bars");
2068 if (bsize == global_control_panel->myLayout->layout()->count())
2070 for (int i = 0; i < bsize; ++i)
2072 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2073 settings.setArrayIndex(i);
2074 if (t->type == type_CvTrackbar)
2076 if (t->name_bar == settings.value("namebar").toString())
2078 ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt());
2081 if (t->type == type_CvButtonbar)
2083 int subsize = settings.beginReadArray(QString("buttonbar")+i);
2085 if ( subsize == ((CvButtonbar*)t)->layout()->count() )
2086 icvLoadButtonbar((CvButtonbar*)t,&settings);
2088 settings.endArray();
2093 settings.endArray();
2097 void CvWindow::icvSaveControlPanel()
2099 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel");
2101 settings.beginWriteArray("bars");
2103 for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i)
2105 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2106 settings.setArrayIndex(i);
2107 if (t->type == type_CvTrackbar)
2109 settings.setValue("namebar", QString(t->name_bar));
2110 settings.setValue("valuebar",((CvTrackbar*)t)->slider->value());
2112 if (t->type == type_CvButtonbar)
2114 settings.beginWriteArray(QString("buttonbar")+i);
2115 icvSaveButtonbar((CvButtonbar*)t,&settings);
2116 settings.endArray();
2120 settings.endArray();
2124 void CvWindow::icvSaveButtonbar(CvButtonbar* b, QSettings* settings)
2126 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2128 settings->setArrayIndex(i);
2130 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2131 QString myclass(QLatin1String(temp->metaObject()->className()));
2133 if (myclass == "CvPushButton")
2135 CvPushButton* button = (CvPushButton*) temp;
2136 settings->setValue("namebutton", button->text());
2137 settings->setValue("valuebutton", int(button->isChecked()));
2139 else if (myclass == "CvCheckBox")
2141 CvCheckBox* button = (CvCheckBox*) temp;
2142 settings->setValue("namebutton", button->text());
2143 settings->setValue("valuebutton", int(button->isChecked()));
2145 else if (myclass == "CvRadioButton")
2147 CvRadioButton* button = (CvRadioButton*) temp;
2148 settings->setValue("namebutton", button->text());
2149 settings->setValue("valuebutton", int(button->isChecked()));
2155 void CvWindow::icvLoadButtonbar(CvButtonbar* b, QSettings* settings)
2157 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2159 settings->setArrayIndex(i);
2161 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2162 QString myclass(QLatin1String(temp->metaObject()->className()));
2164 if (myclass == "CvPushButton")
2166 CvPushButton* button = (CvPushButton*) temp;
2168 if (button->text() == settings->value("namebutton").toString())
2169 button->setChecked(settings->value("valuebutton").toInt());
2171 else if (myclass == "CvCheckBox")
2173 CvCheckBox* button = (CvCheckBox*) temp;
2175 if (button->text() == settings->value("namebutton").toString())
2176 button->setChecked(settings->value("valuebutton").toInt());
2178 else if (myclass == "CvRadioButton")
2180 CvRadioButton* button = (CvRadioButton*) temp;
2182 if (button->text() == settings->value("namebutton").toString())
2183 button->setChecked(settings->value("valuebutton").toInt());
2190 void CvWindow::icvLoadTrackbars(QSettings* settings)
2192 int bsize = settings->beginReadArray("trackbars");
2194 //trackbar are saved in the same order, so no need to use icvFindTrackbarByName
2196 if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)
2198 for (int i = 0; i < bsize; ++i)
2200 settings->setArrayIndex(i);
2202 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2204 if (t->name_bar == settings->value("name").toString())
2205 t->slider->setValue(settings->value("value").toInt());
2210 settings->endArray();
2214 void CvWindow::icvSaveTrackbars(QSettings* settings)
2216 settings->beginWriteArray("trackbars");
2218 for (int i = 0; i < myBarLayout->layout()->count(); ++i)
2220 settings->setArrayIndex(i);
2222 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2224 settings->setValue("name", t->name_bar);
2225 settings->setValue("value", t->slider->value());
2228 settings->endArray();
2232 //////////////////////////////////////////////////////
2236 DefaultViewPort::DefaultViewPort(CvWindow* arg, int arg2) : QGraphicsView(arg), image2Draw_mat(0)
2238 centralWidget = arg;
2239 param_keepRatio = arg2;
2241 setContentsMargins(0, 0, 0, 0);
2242 setMinimumSize(1, 1);
2243 setAlignment(Qt::AlignHCenter);
2245 setObjectName(QString::fromUtf8("graphicsView"));
2247 timerDisplay = new QTimer(this);
2248 timerDisplay->setSingleShot(true);
2249 connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo()));
2252 positionGrabbing = QPointF(0, 0);
2253 positionCorners = QRect(0, 0, size().width(), size().height());
2257 mouseCoordinate = QPoint(-1, -1);
2260 setStyleSheet( "QGraphicsView { border-style: none; }" );
2262 image2Draw_mat = cvCreateMat(viewport()->height(), viewport()->width(), CV_8UC3);
2263 cvZero(image2Draw_mat);
2265 nbChannelOriginImage = 0;
2267 setInteractive(false);
2268 setMouseTracking(true); //receive mouse event everytime
2272 DefaultViewPort::~DefaultViewPort()
2275 cvReleaseMat(&image2Draw_mat);
2279 QWidget* DefaultViewPort::getWidget()
2285 void DefaultViewPort::setMouseCallBack(CvMouseCallback m, void* param)
2289 on_mouse_param = param;
2292 void DefaultViewPort::writeSettings(QSettings& settings)
2294 settings.setValue("matrix_view.m11", param_matrixWorld.m11());
2295 settings.setValue("matrix_view.m12", param_matrixWorld.m12());
2296 settings.setValue("matrix_view.m13", param_matrixWorld.m13());
2297 settings.setValue("matrix_view.m21", param_matrixWorld.m21());
2298 settings.setValue("matrix_view.m22", param_matrixWorld.m22());
2299 settings.setValue("matrix_view.m23", param_matrixWorld.m23());
2300 settings.setValue("matrix_view.m31", param_matrixWorld.m31());
2301 settings.setValue("matrix_view.m32", param_matrixWorld.m32());
2302 settings.setValue("matrix_view.m33", param_matrixWorld.m33());
2306 void DefaultViewPort::readSettings(QSettings& settings)
2308 qreal m11 = settings.value("matrix_view.m11", param_matrixWorld.m11()).toDouble();
2309 qreal m12 = settings.value("matrix_view.m12", param_matrixWorld.m12()).toDouble();
2310 qreal m13 = settings.value("matrix_view.m13", param_matrixWorld.m13()).toDouble();
2311 qreal m21 = settings.value("matrix_view.m21", param_matrixWorld.m21()).toDouble();
2312 qreal m22 = settings.value("matrix_view.m22", param_matrixWorld.m22()).toDouble();
2313 qreal m23 = settings.value("matrix_view.m23", param_matrixWorld.m23()).toDouble();
2314 qreal m31 = settings.value("matrix_view.m31", param_matrixWorld.m31()).toDouble();
2315 qreal m32 = settings.value("matrix_view.m32", param_matrixWorld.m32()).toDouble();
2316 qreal m33 = settings.value("matrix_view.m33", param_matrixWorld.m33()).toDouble();
2318 param_matrixWorld = QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33);
2322 double DefaultViewPort::getRatio()
2324 return param_keepRatio;
2328 void DefaultViewPort::setRatio(int flags)
2330 if (getRatio() == flags) //nothing to do
2334 if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO)
2336 centralWidget->param_ratio_mode = flags;
2337 param_keepRatio = flags;
2339 viewport()->update();
2344 void DefaultViewPort::updateImage(const CvArr* arr)
2351 if (CV_IS_IMAGE_HDR(arr))
2352 origin = ((IplImage*)arr)->origin;
2354 mat = cvGetMat(arr, &stub);
2356 if (!image2Draw_mat || !CV_ARE_SIZES_EQ(image2Draw_mat, mat))
2359 cvReleaseMat(&image2Draw_mat);
2361 //the image in ipl (to do a deep copy with cvCvtColor)
2362 image2Draw_mat = cvCreateMat(mat->rows, mat->cols, CV_8UC3);
2363 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows, image2Draw_mat->step, QImage::Format_RGB888);
2365 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2366 ratioX = width() / float(image2Draw_mat->cols);
2367 ratioY = height() / float(image2Draw_mat->rows);
2372 nbChannelOriginImage = cvGetElemType(mat);
2374 cvConvertImage(mat, image2Draw_mat, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB);
2376 viewport()->update();
2380 void DefaultViewPort::startDisplayInfo(QString text, int delayms)
2382 if (timerDisplay->isActive())
2386 if (delayms > 0) timerDisplay->start(delayms);
2391 void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
2393 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2397 void DefaultViewPort::makeCurrentOpenGlContext()
2399 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2403 void DefaultViewPort::updateGl()
2405 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2409 //Note: move 2 percent of the window
2410 void DefaultViewPort::siftWindowOnLeft()
2412 float delta = 2 * width() / (100.0 * param_matrixWorld.m11());
2413 moveView(QPointF(delta, 0));
2417 //Note: move 2 percent of the window
2418 void DefaultViewPort::siftWindowOnRight()
2420 float delta = -2 * width() / (100.0 * param_matrixWorld.m11());
2421 moveView(QPointF(delta, 0));
2425 //Note: move 2 percent of the window
2426 void DefaultViewPort::siftWindowOnUp()
2428 float delta = 2 * height() / (100.0 * param_matrixWorld.m11());
2429 moveView(QPointF(0, delta));
2433 //Note: move 2 percent of the window
2434 void DefaultViewPort::siftWindowOnDown()
2436 float delta = -2 * height() / (100.0 * param_matrixWorld.m11());
2437 moveView(QPointF(0, delta));
2441 void DefaultViewPort::imgRegion()
2443 scaleView((threshold_zoom_img_region / param_matrixWorld.m11() - 1) * 5, QPointF(size().width() / 2, size().height() / 2));
2447 void DefaultViewPort::resetZoom()
2449 param_matrixWorld.reset();
2450 controlImagePosition();
2454 void DefaultViewPort::ZoomIn()
2456 scaleView(0.5, QPointF(size().width() / 2, size().height() / 2));
2460 void DefaultViewPort::ZoomOut()
2462 scaleView(-0.5, QPointF(size().width() / 2, size().height() / 2));
2466 //can save as JPG, JPEG, BMP, PNG
2467 void DefaultViewPort::saveView()
2469 QDate date_d = QDate::currentDate();
2470 QString date_s = date_d.toString("dd.MM.yyyy");
2471 QString name_s = centralWidget->windowTitle() + "_screenshot_" + date_s;
2473 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s + ".png", tr("Images (*.png *.jpg *.bmp *.jpeg)"));
2475 if (!fileName.isEmpty()) //save the picture
2477 QString extension = fileName.right(3);
2479 // Create a new pixmap to render the viewport into
2480 QPixmap viewportPixmap(viewport()->size());
2481 viewport()->render(&viewportPixmap);
2484 if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
2486 viewportPixmap.save(fileName, "PNG");
2490 if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
2492 viewportPixmap.save(fileName, "JPG");
2496 if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
2498 viewportPixmap.save(fileName, "BMP");
2502 if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
2504 viewportPixmap.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 //overlay pixel values if zoomed in far enough
2655 if (param_matrixWorld.m11()*ratioX >= threshold_zoom_img_region &&
2656 param_matrixWorld.m11()*ratioY >= threshold_zoom_img_region)
2658 drawImgRegion(&myPainter);
2661 //in mode zoom/panning
2662 if (param_matrixWorld.m11() > 1)
2664 drawViewOverview(&myPainter);
2667 //for information overlay
2669 drawInstructions(&myPainter);
2672 if (centralWidget->myStatusBar)
2675 QGraphicsView::paintEvent(evnt);
2679 void DefaultViewPort::stopDisplayInfo()
2681 timerDisplay->stop();
2686 inline bool DefaultViewPort::isSameSize(IplImage* img1, IplImage* img2)
2688 return img1->width == img2->width && img1->height == img2->height;
2692 void DefaultViewPort::controlImagePosition()
2694 qreal left, top, right, bottom;
2696 //after check top-left, bottom right corner to avoid getting "out" during zoom/panning
2697 param_matrixWorld.map(0,0,&left,&top);
2701 param_matrixWorld.translate(-left,0);
2706 param_matrixWorld.translate(0,-top);
2711 QSize sizeImage = size();
2712 param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom);
2713 if (right < sizeImage.width())
2715 param_matrixWorld.translate(sizeImage.width()-right,0);
2716 right = sizeImage.width();
2718 if (bottom < sizeImage.height())
2720 param_matrixWorld.translate(0,sizeImage.height()-bottom);
2721 bottom = sizeImage.height();
2724 //save corner position
2725 positionCorners.setTopLeft(QPoint(left,top));
2726 positionCorners.setBottomRight(QPoint(right,bottom));
2727 //save also the inv matrix
2728 matrixWorld_inv = param_matrixWorld.inverted();
2730 //viewport()->update();
2733 void DefaultViewPort::moveView(QPointF delta)
2735 param_matrixWorld.translate(delta.x(),delta.y());
2736 controlImagePosition();
2737 viewport()->update();
2740 //factor is -0.5 (zoom out) or 0.5 (zoom in)
2741 void DefaultViewPort::scaleView(qreal factor,QPointF center)
2743 factor/=5;//-0.1 <-> 0.1
2744 factor+=1;//0.9 <-> 1.1
2746 //limit zoom out ---
2747 if (param_matrixWorld.m11()==1 && factor < 1)
2750 if (param_matrixWorld.m11()*factor<1)
2751 factor = 1/param_matrixWorld.m11();
2754 //limit zoom int ---
2755 if (param_matrixWorld.m11()>100 && factor > 1)
2758 //inverse the transform
2760 matrixWorld_inv.map(center.x(),center.y(),&a,&b);
2762 param_matrixWorld.translate(a-factor*a,b-factor*b);
2763 param_matrixWorld.scale(factor,factor);
2765 controlImagePosition();
2768 if (centralWidget->myStatusBar)
2769 centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000);
2771 if (param_matrixWorld.m11()>1)
2772 setCursor(Qt::OpenHandCursor);
2778 //up, down, dclick, move
2779 void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)
2781 Qt::KeyboardModifiers modifiers = evnt->modifiers();
2782 Qt::MouseButtons buttons = evnt->buttons();
2785 if(modifiers & Qt::ShiftModifier)
2786 flags |= CV_EVENT_FLAG_SHIFTKEY;
2787 if(modifiers & Qt::ControlModifier)
2788 flags |= CV_EVENT_FLAG_CTRLKEY;
2789 if(modifiers & Qt::AltModifier)
2790 flags |= CV_EVENT_FLAG_ALTKEY;
2792 if(buttons & Qt::LeftButton)
2793 flags |= CV_EVENT_FLAG_LBUTTON;
2794 if(buttons & Qt::RightButton)
2795 flags |= CV_EVENT_FLAG_RBUTTON;
2796 if(buttons & Qt::MidButton)
2797 flags |= CV_EVENT_FLAG_MBUTTON;
2799 cv_event = CV_EVENT_MOUSEMOVE;
2800 switch(evnt->button())
2802 case Qt::LeftButton:
2803 cv_event = tableMouseButtons[category][0];
2804 flags |= CV_EVENT_FLAG_LBUTTON;
2806 case Qt::RightButton:
2807 cv_event = tableMouseButtons[category][1];
2808 flags |= CV_EVENT_FLAG_RBUTTON;
2811 cv_event = tableMouseButtons[category][2];
2812 flags |= CV_EVENT_FLAG_MBUTTON;
2819 void DefaultViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
2821 //to convert mouse coordinate
2823 matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy);
2825 mouseCoordinate.rx()=floor(pfx/ratioX);
2826 mouseCoordinate.ry()=floor(pfy/ratioY);
2829 on_mouse( cv_event, mouseCoordinate.x(),
2830 mouseCoordinate.y(), flags, on_mouse_param );
2834 QSize DefaultViewPort::sizeHint() const
2837 return QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2839 return QGraphicsView::sizeHint();
2843 void DefaultViewPort::draw2D(QPainter *painter)
2845 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888);
2846 painter->drawImage(QRect(0,0,viewport()->width(),viewport()->height()), image2Draw_qt, QRect(0,0, image2Draw_qt.width(), image2Draw_qt.height()) );
2849 //only if CV_8UC1 or CV_8UC3
2850 void DefaultViewPort::drawStatusBar()
2852 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2855 if (mouseCoordinate.x()>=0 &&
2856 mouseCoordinate.y()>=0 &&
2857 mouseCoordinate.x()<image2Draw_qt.width() &&
2858 mouseCoordinate.y()<image2Draw_qt.height())
2859 // if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0)
2861 QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate);
2863 if (nbChannelOriginImage==CV_8UC3 )
2865 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2866 .arg(mouseCoordinate.x())
2867 .arg(mouseCoordinate.y())+
2868 tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+
2869 tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+
2870 tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2])
2874 if (nbChannelOriginImage==CV_8UC1)
2876 //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed
2877 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2878 .arg(mouseCoordinate.x())
2879 .arg(mouseCoordinate.y())+
2880 tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue))
2886 //accept only CV_8UC1 and CV_8UC8 image for now
2887 void DefaultViewPort::drawImgRegion(QPainter *painter)
2889 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2892 double pixel_width = param_matrixWorld.m11()*ratioX;
2893 double pixel_height = param_matrixWorld.m11()*ratioY;
2895 qreal offsetX = param_matrixWorld.dx()/pixel_width;
2896 offsetX = offsetX - floor(offsetX);
2897 qreal offsetY = param_matrixWorld.dy()/pixel_height;
2898 offsetY = offsetY - floor(offsetY);
2900 QSize view = size();
2901 QVarLengthArray<QLineF, 30> linesX;
2902 for (qreal _x = offsetX*pixel_width; _x < view.width(); _x += pixel_width )
2903 linesX.append(QLineF(_x, 0, _x, view.height()));
2905 QVarLengthArray<QLineF, 30> linesY;
2906 for (qreal _y = offsetY*pixel_height; _y < view.height(); _y += pixel_height )
2907 linesY.append(QLineF(0, _y, view.width(), _y));
2910 QFont f = painter->font();
2911 int original_font_size = f.pointSize();
2913 //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2914 f.setPixelSize(10+(pixel_height-threshold_zoom_img_region)/5);
2915 painter->setFont(f);
2918 for (int j=-1;j<height()/pixel_height;j++)//-1 because display the pixels top rows left columns
2919 for (int i=-1;i<width()/pixel_width;i++)//-1
2921 // Calculate top left of the pixel's position in the viewport (screen space)
2922 QPointF pos_in_view((i+offsetX)*pixel_width, (j+offsetY)*pixel_height);
2924 // Calculate top left of the pixel's position in the image (image space)
2925 QPointF pos_in_image = matrixWorld_inv.map(pos_in_view);// Top left of pixel in view
2926 pos_in_image.rx() = pos_in_image.x()/ratioX;
2927 pos_in_image.ry() = pos_in_image.y()/ratioY;
2928 QPoint point_in_image(pos_in_image.x() + 0.5f,pos_in_image.y() + 0.5f);// Add 0.5 for rounding
2931 if (image2Draw_qt.valid(point_in_image))
2932 rgbValue = image2Draw_qt.pixel(point_in_image);
2934 rgbValue = qRgb(0,0,0);
2936 if (nbChannelOriginImage==CV_8UC3)
2940 val = tr("%1 %2").arg(point2.x()).arg(point2.y());
2941 painter->setPen(QPen(Qt::black, 1));
2942 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
2943 Qt::AlignCenter, val);
2947 val = tr("%1").arg(qRed(rgbValue));
2948 painter->setPen(QPen(Qt::red, 1));
2949 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height/3),
2950 Qt::AlignCenter, val);
2952 val = tr("%1").arg(qGreen(rgbValue));
2953 painter->setPen(QPen(Qt::green, 1));
2954 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+pixel_height/3,pixel_width,pixel_height/3),
2955 Qt::AlignCenter, val);
2957 val = tr("%1").arg(qBlue(rgbValue));
2958 painter->setPen(QPen(Qt::blue, 1));
2959 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+2*pixel_height/3,pixel_width,pixel_height/3),
2960 Qt::AlignCenter, val);
2964 if (nbChannelOriginImage==CV_8UC1)
2966 QString val = tr("%1").arg(qRed(rgbValue));
2967 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height),
2968 Qt::AlignCenter, val);
2972 painter->setPen(QPen(Qt::black, 1));
2973 painter->drawLines(linesX.data(), linesX.size());
2974 painter->drawLines(linesY.data(), linesY.size());
2977 f.setPointSize(original_font_size);
2978 painter->setFont(f);
2982 void DefaultViewPort::drawViewOverview(QPainter *painter)
2984 QSize viewSize = size();
2985 viewSize.scale ( 100, 100,Qt::KeepAspectRatio );
2987 const int margin = 5;
2989 //draw the image's location
2990 painter->setBrush(QColor(0, 0, 0, 127));
2991 painter->setPen(Qt::darkGreen);
2992 painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height()));
2994 //daw the view's location inside the image
2995 qreal ratioSize = 1/param_matrixWorld.m11();
2996 qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height());
2997 painter->setPen(Qt::darkBlue);
2998 painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin,
2999 -positionCorners.top()*ratioSize*ratioWindow,
3000 (viewSize.width()-1)*ratioSize,
3001 (viewSize.height()-1)*ratioSize)
3005 void DefaultViewPort::drawInstructions(QPainter *painter)
3007 QFontMetrics metrics = QFontMetrics(font());
3008 int border = qMax(4, metrics.leading());
3010 QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
3011 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3012 painter->setRenderHint(QPainter::TextAntialiasing);
3013 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3014 QColor(0, 0, 0, 127));
3015 painter->setPen(Qt::white);
3016 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3017 QColor(0, 0, 0, 127));
3019 painter->drawText((width() - qrect.width())/2, border,
3020 qrect.width(), qrect.height(),
3021 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3025 void DefaultViewPort::setSize(QSize /*size_*/)
3030 //////////////////////////////////////////////////////
3033 #ifdef HAVE_QT_OPENGL
3035 OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)
3044 OpenGlViewPort::~OpenGlViewPort()
3048 QWidget* OpenGlViewPort::getWidget()
3053 void OpenGlViewPort::setMouseCallBack(CvMouseCallback callback, void* param)
3055 mouseCallback = callback;
3059 void OpenGlViewPort::writeSettings(QSettings& /*settings*/)
3063 void OpenGlViewPort::readSettings(QSettings& /*settings*/)
3067 double OpenGlViewPort::getRatio()
3069 return (double)width() / height();
3072 void OpenGlViewPort::setRatio(int /*flags*/)
3076 void OpenGlViewPort::updateImage(const CvArr* /*arr*/)
3080 void OpenGlViewPort::startDisplayInfo(QString /*text*/, int /*delayms*/)
3084 void OpenGlViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
3086 glDrawCallback = callback;
3087 glDrawData = userdata;
3090 void OpenGlViewPort::makeCurrentOpenGlContext()
3095 void OpenGlViewPort::updateGl()
3097 QGLWidget::updateGL();
3100 void OpenGlViewPort::initializeGL()
3102 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3105 void OpenGlViewPort::resizeGL(int w, int h)
3107 glViewport(0, 0, w, h);
3110 void OpenGlViewPort::paintGL()
3112 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3115 glDrawCallback(glDrawData);
3118 void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)
3120 int cv_event = -1, flags = 0;
3121 QPoint pt = evnt->pos();
3123 icvmouseHandler(evnt, mouse_down, cv_event, flags);
3124 icvmouseProcessing(QPointF(pt), cv_event, flags);
3126 QGLWidget::mousePressEvent(evnt);
3130 void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)
3132 int cv_event = -1, flags = 0;
3133 QPoint pt = evnt->pos();
3135 icvmouseHandler(evnt, mouse_up, cv_event, flags);
3136 icvmouseProcessing(QPointF(pt), cv_event, flags);
3138 QGLWidget::mouseReleaseEvent(evnt);
3142 void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
3144 int cv_event = -1, flags = 0;
3145 QPoint pt = evnt->pos();
3147 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
3148 icvmouseProcessing(QPointF(pt), cv_event, flags);
3150 QGLWidget::mouseDoubleClickEvent(evnt);
3154 void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)
3156 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
3157 QPoint pt = evnt->pos();
3159 //icvmouseHandler: pass parameters for cv_event, flags
3160 icvmouseHandler(evnt, mouse_move, cv_event, flags);
3161 icvmouseProcessing(QPointF(pt), cv_event, flags);
3163 QGLWidget::mouseMoveEvent(evnt);
3166 void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)
3168 Qt::KeyboardModifiers modifiers = evnt->modifiers();
3169 Qt::MouseButtons buttons = evnt->buttons();
3172 if (modifiers & Qt::ShiftModifier)
3173 flags |= CV_EVENT_FLAG_SHIFTKEY;
3174 if (modifiers & Qt::ControlModifier)
3175 flags |= CV_EVENT_FLAG_CTRLKEY;
3176 if (modifiers & Qt::AltModifier)
3177 flags |= CV_EVENT_FLAG_ALTKEY;
3179 if (buttons & Qt::LeftButton)
3180 flags |= CV_EVENT_FLAG_LBUTTON;
3181 if (buttons & Qt::RightButton)
3182 flags |= CV_EVENT_FLAG_RBUTTON;
3183 if (buttons & Qt::MidButton)
3184 flags |= CV_EVENT_FLAG_MBUTTON;
3186 cv_event = CV_EVENT_MOUSEMOVE;
3187 switch (evnt->button())
3189 case Qt::LeftButton:
3190 cv_event = tableMouseButtons[category][0];
3191 flags |= CV_EVENT_FLAG_LBUTTON;
3194 case Qt::RightButton:
3195 cv_event = tableMouseButtons[category][1];
3196 flags |= CV_EVENT_FLAG_RBUTTON;
3200 cv_event = tableMouseButtons[category][2];
3201 flags |= CV_EVENT_FLAG_MBUTTON;
3210 void OpenGlViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
3213 mouseCallback(cv_event, pt.x(), pt.y(), flags, mouseData);
3217 QSize OpenGlViewPort::sizeHint() const
3219 if (size.width() > 0 && size.height() > 0)
3222 return QGLWidget::sizeHint();
3225 void OpenGlViewPort::setSize(QSize size_)