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));
185 void cvSetModeWindow_QT(const char* name, double prop_value)
188 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
190 QMetaObject::invokeMethod(guiMainThread,
192 autoBlockingConnection(),
193 Q_ARG(QString, QString(name)),
194 Q_ARG(double, prop_value));
198 double cvGetModeWindow_QT(const char* name)
201 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
205 QMetaObject::invokeMethod(guiMainThread,
207 autoBlockingConnection(),
208 Q_RETURN_ARG(double, result),
209 Q_ARG(QString, QString(name)));
215 CV_IMPL void cvDisplayOverlay(const char* name, const char* text, int delayms)
218 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
220 QMetaObject::invokeMethod(guiMainThread,
222 autoBlockingConnection(),
223 Q_ARG(QString, QString(name)),
224 Q_ARG(QString, QString(text)),
225 Q_ARG(int, delayms));
229 CV_IMPL void cvSaveWindowParameters(const char* name)
232 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
234 QMetaObject::invokeMethod(guiMainThread,
235 "saveWindowParameters",
236 autoBlockingConnection(),
237 Q_ARG(QString, QString(name)));
241 CV_IMPL void cvLoadWindowParameters(const char* name)
244 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
246 QMetaObject::invokeMethod(guiMainThread,
247 "loadWindowParameters",
248 autoBlockingConnection(),
249 Q_ARG(QString, QString(name)));
253 CV_IMPL void cvDisplayStatusBar(const char* name, const char* text, int delayms)
256 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
258 QMetaObject::invokeMethod(guiMainThread,
260 autoBlockingConnection(),
261 Q_ARG(QString, QString(name)),
262 Q_ARG(QString, QString(text)),
263 Q_ARG(int, delayms));
267 CV_IMPL int cvWaitKey(int delay)
274 unsigned long delayms = delay <= 0 ? ULONG_MAX : delay; //in milliseconds
279 if (key_pressed.wait(&mutexKey, delayms)) //false if timeout
288 //cannot use wait here because events will not be distributed before processEvents (the main eventLoop is broken)
289 //so I create a Thread for the QTimer
292 guiMainThread->timer->start(delay);
296 while (!guiMainThread->bTimeOut)
298 qApp->processEvents(QEventLoop::AllEvents);
300 if (!guiMainThread)//when all the windows are deleted
308 guiMainThread->timer->stop();
309 //printf("keypressed\n");
320 * //will not work, I broke the event loop !!!!
322 QWaitCondition waitCondition;
323 waitCondition.wait(&dummy, 2);
326 //to decrease CPU usage
327 //sleep 1 millisecond
328 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
336 guiMainThread->bTimeOut = false;
343 //This function is experimental and some functions (such as cvSet/getWindowProperty will not work)
344 //We recommend not using this function for now
345 CV_IMPL int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[])
348 QFuture<int> future = QtConcurrent::run(pt2Func, argc, argv);
349 return guiMainThread->start();
353 CV_IMPL void cvStopLoop()
359 static CvWindow* icvFindWindowByName(QString name)
361 CvWindow* window = 0;
363 //This is not a very clean way to do the stuff. Indeed, QAction automatically generate toolTil (QLabel)
364 //that can be grabbed here and crash the code at 'w->param_name==name'.
365 foreach (QWidget* widget, QApplication::topLevelWidgets())
367 if (widget->isWindow() && !widget->parentWidget())//is a window without parent
369 CvWinModel* temp = (CvWinModel*) widget;
371 if (temp->type == type_CvWindow)
373 CvWindow* w = (CvWindow*) temp;
374 if (w->windowTitle() == name)
387 static CvBar* icvFindBarByName(QBoxLayout* layout, QString name_bar, typeBar type)
392 int stop_index = layout->layout()->count();
394 for (int i = 0; i < stop_index; ++i)
396 CvBar* t = (CvBar*) layout->layout()->itemAt(i);
398 if (t->type == type && t->name_bar == name_bar)
406 static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char* name_window, QBoxLayout* layout = NULL)
408 QString nameQt(name_trackbar);
409 if ((!name_window || !name_window[0]) && global_control_panel) //window name is null and we have a control panel
410 layout = global_control_panel->myLayout;
414 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(name_window));
417 CV_Error(CV_StsNullPtr, "NULL window handler");
419 if (w->param_gui_mode == CV_GUI_NORMAL)
420 return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
422 if (w->param_gui_mode == CV_GUI_EXPANDED)
424 CvBar* result = icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
427 return (CvTrackbar*) result;
429 return (CvTrackbar*) icvFindBarByName(global_control_panel->myLayout, nameQt, type_CvTrackbar);
436 //layout was specified
437 return (CvTrackbar*) icvFindBarByName(layout, nameQt, type_CvTrackbar);
442 static CvButtonbar* icvFindButtonBarByName(const char* button_name, QBoxLayout* layout)
444 QString nameQt(button_name);
445 return (CvButtonbar*) icvFindBarByName(layout, nameQt, type_CvButtonbar);
449 static int icvInitSystem(int* c, char** v)
451 //"For any GUI application using Qt, there is precisely one QApplication object"
452 if (!QApplication::instance())
454 new QApplication(*c, v);
456 qDebug() << "init done";
458 #ifdef HAVE_QT_OPENGL
459 qDebug() << "opengl support available";
467 CV_IMPL int cvInitSystem(int, char**)
469 icvInitSystem(¶meterSystemC, parameterSystemV);
474 CV_IMPL int cvNamedWindow(const char* name, int flags)
477 guiMainThread = new GuiReceiver;
478 if (QThread::currentThread() != QApplication::instance()->thread()) {
480 QMetaObject::invokeMethod(guiMainThread,
482 Qt::BlockingQueuedConnection, // block so that we can do useful stuff once we confirm it is created
483 Q_ARG(QString, QString(name)),
486 guiMainThread->createWindow(QString(name), flags);
489 return 1; //Dummy value - probably should return the result of the invocation.
493 CV_IMPL void cvDestroyWindow(const char* name)
496 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
498 QMetaObject::invokeMethod(guiMainThread,
500 Qt::AutoConnection, // if another thread is controlling, let it handle it without blocking ourselves here
501 Q_ARG(QString, QString(name)));
505 CV_IMPL void cvDestroyAllWindows()
509 QMetaObject::invokeMethod(guiMainThread,
511 Qt::AutoConnection // if another thread is controlling, let it handle it without blocking ourselves here
516 CV_IMPL void* cvGetWindowHandle(const char* name)
519 CV_Error( CV_StsNullPtr, "NULL name string" );
521 return (void*) icvFindWindowByName(QLatin1String(name));
525 CV_IMPL const char* cvGetWindowName(void* window_handle)
528 CV_Error( CV_StsNullPtr, "NULL window handler" );
530 return ((CvWindow*)window_handle)->windowTitle().toLatin1().data();
534 CV_IMPL void cvMoveWindow(const char* name, int x, int y)
537 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
538 QMetaObject::invokeMethod(guiMainThread,
540 autoBlockingConnection(),
541 Q_ARG(QString, QString(name)),
546 CV_IMPL void cvResizeWindow(const char* name, int width, int height)
549 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
550 QMetaObject::invokeMethod(guiMainThread,
552 autoBlockingConnection(),
553 Q_ARG(QString, QString(name)),
559 CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata)
562 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
564 QMetaObject::invokeMethod(guiMainThread,
566 autoBlockingConnection(),
567 Q_ARG(QString, QString(name_bar)),
568 Q_ARG(QString, QString(window_name)),
569 Q_ARG(void*, (void*)val),
571 Q_ARG(void*, (void*)on_notify),
572 Q_ARG(void*, (void*)userdata));
574 return 1; //dummy value
578 CV_IMPL int cvStartWindowThread()
584 CV_IMPL int cvCreateTrackbar(const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change)
587 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
589 QMetaObject::invokeMethod(guiMainThread,
591 autoBlockingConnection(),
592 Q_ARG(QString, QString(name_bar)),
593 Q_ARG(QString, QString(window_name)),
594 Q_ARG(void*, (void*)value),
596 Q_ARG(void*, (void*)on_change));
598 return 1; //dummy value
602 CV_IMPL int cvCreateButton(const char* button_name, CvButtonCallback on_change, void* userdata, int button_type, int initial_button_state)
605 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
607 if (initial_button_state < 0 || initial_button_state > 1)
610 QMetaObject::invokeMethod(guiMainThread,
612 autoBlockingConnection(),
613 Q_ARG(QString, QString(button_name)),
614 Q_ARG(int, button_type),
615 Q_ARG(int, initial_button_state),
616 Q_ARG(void*, (void*)on_change),
617 Q_ARG(void*, userdata));
619 return 1;//dummy value
623 CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name)
627 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
630 result = t->slider->value();
636 CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int pos)
638 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
641 t->slider->setValue(pos);
645 /* assign callback for mouse events */
646 CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param)
648 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
651 CV_Error(CV_StsNullPtr, "NULL window handler");
653 w->setMouseCallBack(on_mouse, param);
658 CV_IMPL void cvShowImage(const char* name, const CvArr* arr)
661 guiMainThread = new GuiReceiver;
662 if (QThread::currentThread() != QApplication::instance()->thread()) {
664 QMetaObject::invokeMethod(guiMainThread,
666 autoBlockingConnection(),
667 Q_ARG(QString, QString(name)),
668 Q_ARG(void*, (void*)arr)
671 guiMainThread->showImage(QString(name), (void*)arr);
676 #ifdef HAVE_QT_OPENGL
678 CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
681 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
683 QMetaObject::invokeMethod(guiMainThread,
684 "setOpenGlDrawCallback",
685 autoBlockingConnection(),
686 Q_ARG(QString, QString(window_name)),
687 Q_ARG(void*, (void*)callback),
688 Q_ARG(void*, userdata));
692 CV_IMPL void cvSetOpenGlContext(const char* window_name)
695 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
697 QMetaObject::invokeMethod(guiMainThread,
699 autoBlockingConnection(),
700 Q_ARG(QString, QString(window_name)));
704 CV_IMPL void cvUpdateWindow(const char* window_name)
707 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
709 QMetaObject::invokeMethod(guiMainThread,
711 autoBlockingConnection(),
712 Q_ARG(QString, QString(window_name)));
718 double cvGetOpenGlProp_QT(const char* name)
724 QMetaObject::invokeMethod(guiMainThread,
726 autoBlockingConnection(),
727 Q_RETURN_ARG(double, result),
728 Q_ARG(QString, QString(name)));
735 //////////////////////////////////////////////////////
739 GuiReceiver::GuiReceiver() : bTimeOut(false), nb_windows(0)
741 doesExternalQAppExist = (QApplication::instance() != 0);
742 icvInitSystem(¶meterSystemC, parameterSystemV);
744 timer = new QTimer(this);
745 QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
746 timer->setSingleShot(true);
747 if ( doesExternalQAppExist ) {
748 moveToThread(QApplication::instance()->thread());
753 void GuiReceiver::isLastWindow()
755 if (--nb_windows <= 0)
757 delete guiMainThread;//delete global_control_panel too
758 guiMainThread = NULL;
760 if (!doesExternalQAppExist)
768 GuiReceiver::~GuiReceiver()
770 if (global_control_panel)
772 delete global_control_panel;
773 global_control_panel = NULL;
778 void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2)
783 mat = cvGetMat(arr, &stub);
785 int nbChannelOriginImage = cvGetElemType(mat);
786 if (nbChannelOriginImage != CV_8UC3) return; //for now, font works only with 8UC3
788 QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888);
790 CvFont* font = (CvFont*)arg2;
795 QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/);
796 f.setStyle((QFont::Style) font->font_face/*style*/);
797 f.setLetterSpacing(QFont::AbsoluteSpacing, font->dx/*spacing*/);
798 //cvScalar(blue_component, green_component, red_component[, alpha_component])
799 //Qt map non-transparent to 0xFF and transparent to 0
800 //OpenCV scalar is the reverse, so 255-font->color.val[3]
801 qp.setPen(QColor(font->color.val[2], font->color.val[1], font->color.val[0], 255 - font->color.val[3]));
804 qp.drawText(org, text);
809 void GuiReceiver::saveWindowParameters(QString name)
811 QPointer<CvWindow> w = icvFindWindowByName(name);
818 void GuiReceiver::loadWindowParameters(QString name)
820 QPointer<CvWindow> w = icvFindWindowByName(name);
827 double GuiReceiver::getRatioWindow(QString name)
829 QPointer<CvWindow> w = icvFindWindowByName(name);
834 return w->getRatio();
838 void GuiReceiver::setRatioWindow(QString name, double arg2)
840 QPointer<CvWindow> w = icvFindWindowByName( name.toLatin1().data() );
845 int flags = (int) arg2;
851 double GuiReceiver::getPropWindow(QString name)
853 QPointer<CvWindow> w = icvFindWindowByName(name);
858 return (double) w->getPropWindow();
862 void GuiReceiver::setPropWindow(QString name, double arg2)
864 QPointer<CvWindow> w = icvFindWindowByName(name);
869 int flags = (int) arg2;
871 w->setPropWindow(flags);
875 double GuiReceiver::isFullScreen(QString name)
877 QPointer<CvWindow> w = icvFindWindowByName(name);
882 return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL;
886 void GuiReceiver::toggleFullScreen(QString name, double arg2)
888 QPointer<CvWindow> w = icvFindWindowByName(name);
893 int flags = (int) arg2;
895 w->toggleFullScreen(flags);
899 void GuiReceiver::createWindow(QString name, int flags)
902 CV_Error(CV_StsNullPtr, "NULL session handler" );
904 // Check the name in the storage
905 if (icvFindWindowByName(name.toLatin1().data()))
911 new CvWindow(name, flags);
915 void GuiReceiver::timeOut()
921 void GuiReceiver::displayInfo(QString name, QString text, int delayms)
923 QPointer<CvWindow> w = icvFindWindowByName(name);
926 w->displayInfo(text, delayms);
930 void GuiReceiver::displayStatusBar(QString name, QString text, int delayms)
932 QPointer<CvWindow> w = icvFindWindowByName(name);
935 w->displayStatusBar(text, delayms);
939 void GuiReceiver::showImage(QString name, void* arr)
941 QPointer<CvWindow> w = icvFindWindowByName(name);
943 if (!w) //as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null
945 cvNamedWindow(name.toLatin1().data());
946 w = icvFindWindowByName(name);
950 return; // keep silence here.
956 mat = cvGetMat(arr, &stub);
958 cv::Mat im = cv::cvarrToMat(mat);
959 cv::imshow(name.toUtf8().data(), im);
971 void GuiReceiver::destroyWindow(QString name)
974 QPointer<CvWindow> w = icvFindWindowByName(name);
980 //in not-multiThreads mode, looks like the window is hidden but not deleted
981 //so I do it manually
982 //otherwise QApplication do it for me if the exec command was executed (in multiThread mode)
989 void GuiReceiver::destroyAllWindow()
992 CV_Error(CV_StsNullPtr, "NULL session handler" );
996 // WARNING: this could even close windows from an external parent app
997 //#TODO check externalQAppExists and in case it does, close windows carefully,
998 // i.e. apply the className-check from below...
999 qApp->closeAllWindows();
1003 bool isWidgetDeleted = true;
1004 while(isWidgetDeleted)
1006 isWidgetDeleted = false;
1007 QWidgetList list = QApplication::topLevelWidgets();
1008 for (int i = 0; i < list.count(); i++)
1010 QObject *obj = list.at(i);
1011 if (obj->metaObject()->className() == QString("CvWindow"))
1014 isWidgetDeleted = true;
1023 void GuiReceiver::moveWindow(QString name, int x, int y)
1025 QPointer<CvWindow> w = icvFindWindowByName(name);
1032 void GuiReceiver::resizeWindow(QString name, int width, int height)
1034 QPointer<CvWindow> w = icvFindWindowByName(name);
1039 w->setViewportSize(QSize(width, height));
1044 void GuiReceiver::enablePropertiesButtonEachWindow()
1046 //For each window, enable window property button
1047 foreach (QWidget* widget, QApplication::topLevelWidgets())
1049 if (widget->isWindow() && !widget->parentWidget()) //is a window without parent
1051 CvWinModel* temp = (CvWinModel*) widget;
1052 if (temp->type == type_CvWindow)
1054 CvWindow* w = (CvWindow*) widget;
1056 //active window properties button
1057 w->enablePropertiesButton();
1064 void GuiReceiver::addButton(QString button_name, int button_type, int initial_button_state, void* on_change, void* userdata)
1066 if (!global_control_panel)
1069 QPointer<CvButtonbar> b;
1071 if (global_control_panel->myLayout->count() == 0) //if that is the first button attach to the control panel, create a new button bar
1073 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1074 enablePropertiesButtonEachWindow();
1079 CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count() - 1);
1081 if (lastbar->type == type_CvTrackbar) //if last bar is a trackbar, create a new buttonbar, else, attach to the current bar
1082 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1084 b = (CvButtonbar*) lastbar;
1088 b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state);
1092 void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata)
1094 QBoxLayout *layout = NULL;
1095 QPointer<CvWindow> w;
1097 if (!window_name.isEmpty())
1099 w = icvFindWindowByName(window_name);
1106 if (global_control_panel)
1107 layout = global_control_panel->myLayout;
1110 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1112 if (t) //trackbar exists
1116 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1118 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1119 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1121 CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
1125 void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change)
1127 QBoxLayout *layout = NULL;
1128 QPointer<CvWindow> w;
1130 if (!window_name.isEmpty())
1132 w = icvFindWindowByName(window_name);
1139 if (global_control_panel)
1140 layout = global_control_panel->myLayout;
1143 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1145 if (t) //trackbar exists
1149 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1151 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1152 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1154 CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
1158 int GuiReceiver::start()
1160 return qApp->exec();
1164 void GuiReceiver::setOpenGlDrawCallback(QString name, void* callback, void* userdata)
1166 QPointer<CvWindow> w = icvFindWindowByName(name);
1169 w->setOpenGlDrawCallback((CvOpenGlDrawCallback) callback, userdata);
1172 void GuiReceiver::setOpenGlContext(QString name)
1174 QPointer<CvWindow> w = icvFindWindowByName(name);
1177 w->makeCurrentOpenGlContext();
1180 void GuiReceiver::updateWindow(QString name)
1182 QPointer<CvWindow> w = icvFindWindowByName(name);
1188 double GuiReceiver::isOpenGl(QString name)
1192 QPointer<CvWindow> w = icvFindWindowByName(name);
1195 result = (double) w->isOpenGl();
1201 //////////////////////////////////////////////////////
1205 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)
1208 callback2 = on_change;
1211 create(arg, name, value, _count);
1215 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)
1217 callback = on_change;
1221 create(arg, name, value, _count);
1225 void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)
1227 type = type_CvTrackbar;
1230 setObjectName(name_bar);
1233 slider = new QSlider(Qt::Horizontal);
1234 slider->setFocusPolicy(Qt::StrongFocus);
1235 slider->setMinimum(0);
1236 slider->setMaximum(_count);
1237 slider->setPageStep(5);
1238 slider->setValue(*value);
1239 slider->setTickPosition(QSlider::TicksBelow);
1242 //Change style of the Slider
1243 //slider->setStyleSheet(str_Trackbar_css);
1245 QFile qss(":/stylesheet-trackbar");
1246 if (qss.open(QFile::ReadOnly))
1248 slider->setStyleSheet(QLatin1String(qss.readAll()));
1253 //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?)
1254 //slider->setTickPosition(QSlider::TicksBelow);
1255 label = new QPushButton;
1256 label->setFlat(true);
1257 setLabel(slider->value());
1260 QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(update(int)));
1262 QObject::connect(label, SIGNAL(clicked()), this, SLOT(createDialog()));
1264 //label->setStyleSheet("QPushButton:disabled {color: black}");
1266 addWidget(label, Qt::AlignLeft);//name + value
1267 addWidget(slider, Qt::AlignCenter);//slider
1271 void CvTrackbar::createDialog()
1275 //crash if I access the values directly and give them to QInputDialog, so do a copy first.
1276 int value = slider->value();
1277 int step = slider->singleStep();
1278 int min = slider->minimum();
1279 int max = slider->maximum();
1282 #if QT_VERSION >= 0x040500
1283 QInputDialog::getInt
1285 QInputDialog::getInteger
1287 (this->parentWidget(),
1288 tr("Slider %1").arg(name_bar),
1297 slider->setValue(i);
1301 void CvTrackbar::update(int myvalue)
1305 *dataSlider = myvalue;
1314 callback2(myvalue, userdata);
1320 void CvTrackbar::setLabel(int myvalue)
1322 QString nameNormalized = name_bar.leftJustified( 10, ' ', true );
1323 QString valueMaximum = QString("%1").arg(slider->maximum());
1324 QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum);
1325 label->setText(str);
1329 //////////////////////////////////////////////////////
1333 //here CvButtonbar class
1334 CvButtonbar::CvButtonbar(QWidget* arg, QString arg2)
1336 type = type_CvButtonbar;
1339 setObjectName(name_bar);
1341 group_button = new QButtonGroup(this);
1345 void CvButtonbar::setLabel()
1347 QString nameNormalized = name_bar.leftJustified(10, ' ', true);
1348 label->setText(nameNormalized);
1352 void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state)
1354 QString button_name = name;
1356 if (button_name == "")
1357 button_name = tr("button %1").arg(this->count());
1359 QPointer<QAbstractButton> button;
1361 if (button_type == CV_PUSH_BUTTON)
1362 button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata);
1364 if (button_type == CV_CHECKBOX)
1365 button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state);
1367 if (button_type == CV_RADIOBOX)
1369 button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state);
1370 group_button->addButton(button);
1375 if (button_type == CV_PUSH_BUTTON)
1376 QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool)));
1378 QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool)));
1380 addWidget(button, Qt::AlignCenter);
1385 //////////////////////////////////////////////////////
1390 CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4)
1397 setObjectName(button_name);
1398 setText(button_name);
1405 void CvPushButton::callCallBack(bool checked)
1408 callback(checked, userdata);
1412 CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1419 setObjectName(button_name);
1420 setCheckState((initial_button_state == 1 ? Qt::Checked : Qt::Unchecked));
1421 setText(button_name);
1428 void CvCheckBox::callCallBack(bool checked)
1431 callback(checked, userdata);
1435 CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1442 setObjectName(button_name);
1443 setChecked(initial_button_state);
1444 setText(button_name);
1450 void CvRadioButton::callCallBack(bool checked)
1453 callback(checked, userdata);
1457 //////////////////////////////////////////////////////
1461 //here CvWinProperties class
1462 CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)
1464 //setParent(parent);
1465 type = type_CvWinProperties;
1466 setWindowFlags(Qt::Tool);
1467 setContentsMargins(0, 0, 0, 0);
1468 setWindowTitle(name_paraWindow);
1469 setObjectName(name_paraWindow);
1472 myLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1473 myLayout->setObjectName(QString::fromUtf8("boxLayout"));
1474 myLayout->setContentsMargins(0, 0, 0, 0);
1475 myLayout->setSpacing(0);
1476 myLayout->setMargin(0);
1477 myLayout->setSizeConstraint(QLayout::SetFixedSize);
1478 setLayout(myLayout);
1484 void CvWinProperties::closeEvent(QCloseEvent* e)
1486 e->accept(); //intersept the close event (not sure I really need it)
1487 //an hide event is also sent. I will intercept it and do some processing
1491 void CvWinProperties::showEvent(QShowEvent* evnt)
1493 //why -1,-1 ?: do this trick because the first time the code is run,
1494 //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).
1495 //then hide will save the last position and thus, we want to retreive it (event accepted).
1496 QPoint mypos(-1, -1);
1497 QSettings settings("OpenCV2", windowTitle());
1498 mypos = settings.value("pos", mypos).toPoint();
1512 void CvWinProperties::hideEvent(QHideEvent* evnt)
1514 QSettings settings("OpenCV2", windowTitle());
1515 settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)
1520 CvWinProperties::~CvWinProperties()
1522 //clear the setting pos
1523 QSettings settings("OpenCV2", windowTitle());
1524 settings.remove("pos");
1528 //////////////////////////////////////////////////////
1532 CvWindow::CvWindow(QString name, int arg2)
1534 type = type_CvWindow;
1536 param_flags = arg2 & 0x0000000F;
1537 param_gui_mode = arg2 & 0x000000F0;
1538 param_ratio_mode = arg2 & 0x00000F00;
1540 //setAttribute(Qt::WA_DeleteOnClose); //in other case, does not release memory
1541 setContentsMargins(0, 0, 0, 0);
1542 setWindowTitle(name);
1543 setObjectName(name);
1545 setFocus( Qt::PopupFocusReason ); //#1695 arrow keys are not received without the explicit focus
1548 setMinimumSize(1, 1);
1550 //1: create control panel
1551 if (!global_control_panel)
1552 global_control_panel = createParameterWindow();
1556 createGlobalLayout();
1559 #ifndef HAVE_QT_OPENGL
1560 if (arg2 & CV_WINDOW_OPENGL)
1561 CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
1562 mode_display = CV_MODE_NORMAL;
1564 mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
1565 if (mode_display == CV_MODE_OPENGL)
1566 param_gui_mode = CV_GUI_NORMAL;
1570 //4: shortcuts and actions
1571 //5: toolBar and statusbar
1572 if (param_gui_mode == CV_GUI_EXPANDED)
1581 //Now attach everything
1583 myGlobalLayout->addWidget(myToolBar, Qt::AlignCenter);
1585 myGlobalLayout->addWidget(myView->getWidget(), Qt::AlignCenter);
1587 myGlobalLayout->addLayout(myBarLayout, Qt::AlignCenter);
1590 myGlobalLayout->addWidget(myStatusBar, Qt::AlignCenter);
1592 setLayout(myGlobalLayout);
1597 CvWindow::~CvWindow()
1600 guiMainThread->isLastWindow();
1604 void CvWindow::setMouseCallBack(CvMouseCallback callback, void* param)
1606 myView->setMouseCallBack(callback, param);
1610 void CvWindow::writeSettings()
1612 //organisation and application's name
1613 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1615 settings.setValue("pos", pos());
1616 settings.setValue("size", size());
1617 settings.setValue("mode_resize" ,param_flags);
1618 settings.setValue("mode_gui", param_gui_mode);
1620 myView->writeSettings(settings);
1622 icvSaveTrackbars(&settings);
1624 if (global_control_panel)
1626 icvSaveControlPanel();
1627 settings.setValue("posPanel", global_control_panel->pos());
1633 //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars)
1634 void CvWindow::readSettings()
1636 //organisation and application's name
1637 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1639 QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();
1640 QSize _size = settings.value("size", QSize(400, 400)).toSize();
1642 param_flags = settings.value("mode_resize", param_flags).toInt();
1643 param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();
1645 param_flags = settings.value("mode_resize", param_flags).toInt();
1647 myView->readSettings(settings);
1650 icvLoadTrackbars(&settings);
1655 if (global_control_panel)
1657 icvLoadControlPanel();
1658 global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint());
1663 double CvWindow::getRatio()
1665 return myView->getRatio();
1669 void CvWindow::setRatio(int flags)
1671 myView->setRatio(flags);
1675 int CvWindow::getPropWindow()
1681 void CvWindow::setPropWindow(int flags)
1683 if (param_flags == flags) //nothing to do
1688 case CV_WINDOW_NORMAL:
1689 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1690 param_flags = flags;
1694 case CV_WINDOW_AUTOSIZE:
1695 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1696 param_flags = flags;
1706 void CvWindow::toggleFullScreen(int flags)
1708 if (isFullScreen() && flags == CV_WINDOW_NORMAL)
1715 if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN)
1724 void CvWindow::updateImage(void* arr)
1726 myView->updateImage(arr);
1730 void CvWindow::displayInfo(QString text, int delayms)
1732 myView->startDisplayInfo(text, delayms);
1736 void CvWindow::displayStatusBar(QString text, int delayms)
1739 myStatusBar->showMessage(text, delayms);
1743 void CvWindow::enablePropertiesButton()
1745 if (!vect_QActions.empty())
1746 vect_QActions[9]->setDisabled(false);
1750 CvButtonbar* CvWindow::createButtonBar(QString name_bar)
1752 QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel, name_bar);
1753 t->setAlignment(Qt::AlignHCenter);
1755 QPointer<QBoxLayout> myLayout = global_control_panel->myLayout;
1757 myLayout->insertLayout(myLayout->count(), t);
1763 void CvWindow::addSlider(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback on_change)
1765 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change);
1766 t->setAlignment(Qt::AlignHCenter);
1768 QPointer<QBoxLayout> myLayout;
1772 myLayout = w->myBarLayout;
1776 myLayout = global_control_panel->myLayout;
1778 //if first one, enable control panel
1779 if (myLayout->count() == 0)
1780 guiMainThread->enablePropertiesButtonEachWindow();
1783 myLayout->insertLayout(myLayout->count(), t);
1787 void CvWindow::addSlider2(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata)
1789 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change, userdata);
1790 t->setAlignment(Qt::AlignHCenter);
1792 QPointer<QBoxLayout> myLayout;
1796 myLayout = w->myBarLayout;
1800 myLayout = global_control_panel->myLayout;
1802 //if first one, enable control panel
1803 if (myLayout->count() == 0)
1804 guiMainThread->enablePropertiesButtonEachWindow();
1807 myLayout->insertLayout(myLayout->count(), t);
1811 void CvWindow::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
1813 myView->setOpenGlDrawCallback(callback, userdata);
1817 void CvWindow::makeCurrentOpenGlContext()
1819 myView->makeCurrentOpenGlContext();
1823 void CvWindow::updateGl()
1829 bool CvWindow::isOpenGl()
1831 return mode_display == CV_MODE_OPENGL;
1835 void CvWindow::setViewportSize(QSize _size)
1837 myView->getWidget()->resize(_size);
1838 myView->setSize(_size);
1842 void CvWindow::createBarLayout()
1844 myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1845 myBarLayout->setObjectName(QString::fromUtf8("barLayout"));
1846 myBarLayout->setContentsMargins(0, 0, 0, 0);
1847 myBarLayout->setSpacing(0);
1848 myBarLayout->setMargin(0);
1852 void CvWindow::createGlobalLayout()
1854 myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1855 myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout"));
1856 myGlobalLayout->setContentsMargins(0, 0, 0, 0);
1857 myGlobalLayout->setSpacing(0);
1858 myGlobalLayout->setMargin(0);
1859 setMinimumSize(1, 1);
1861 if (param_flags == CV_WINDOW_AUTOSIZE)
1862 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1863 else if (param_flags == CV_WINDOW_NORMAL)
1864 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1868 void CvWindow::createView()
1870 #ifdef HAVE_QT_OPENGL
1872 myView = new OpenGlViewPort(this);
1875 myView = new DefaultViewPort(this, param_ratio_mode);
1879 void CvWindow::createActions()
1881 vect_QActions.resize(10);
1883 QWidget* view = myView->getWidget();
1885 //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually
1886 vect_QActions[0] = new QAction(QIcon(":/left-icon"), "Panning left (CTRL+arrowLEFT)", this);
1887 vect_QActions[0]->setIconVisibleInMenu(true);
1888 QObject::connect(vect_QActions[0], SIGNAL(triggered()), view, SLOT(siftWindowOnLeft()));
1890 vect_QActions[1] = new QAction(QIcon(":/right-icon"), "Panning right (CTRL+arrowRIGHT)", this);
1891 vect_QActions[1]->setIconVisibleInMenu(true);
1892 QObject::connect(vect_QActions[1], SIGNAL(triggered()), view, SLOT(siftWindowOnRight()));
1894 vect_QActions[2] = new QAction(QIcon(":/up-icon"), "Panning up (CTRL+arrowUP)", this);
1895 vect_QActions[2]->setIconVisibleInMenu(true);
1896 QObject::connect(vect_QActions[2], SIGNAL(triggered()), view, SLOT(siftWindowOnUp()));
1898 vect_QActions[3] = new QAction(QIcon(":/down-icon"), "Panning down (CTRL+arrowDOWN)", this);
1899 vect_QActions[3]->setIconVisibleInMenu(true);
1900 QObject::connect(vect_QActions[3], SIGNAL(triggered()), view, SLOT(siftWindowOnDown()) );
1902 vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"), "Zoom x1 (CTRL+P)", this);
1903 vect_QActions[4]->setIconVisibleInMenu(true);
1904 QObject::connect(vect_QActions[4], SIGNAL(triggered()), view, SLOT(resetZoom()));
1906 vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"), tr("Zoom x%1 (see label) (CTRL+X)").arg(threshold_zoom_img_region), this);
1907 vect_QActions[5]->setIconVisibleInMenu(true);
1908 QObject::connect(vect_QActions[5], SIGNAL(triggered()), view, SLOT(imgRegion()));
1910 vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"), "Zoom in (CTRL++)", this);
1911 vect_QActions[6]->setIconVisibleInMenu(true);
1912 QObject::connect(vect_QActions[6], SIGNAL(triggered()), view, SLOT(ZoomIn()));
1914 vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"), "Zoom out (CTRL+-)", this);
1915 vect_QActions[7]->setIconVisibleInMenu(true);
1916 QObject::connect(vect_QActions[7], SIGNAL(triggered()), view, SLOT(ZoomOut()));
1918 vect_QActions[8] = new QAction(QIcon(":/save-icon"), "Save current image (CTRL+S)", this);
1919 vect_QActions[8]->setIconVisibleInMenu(true);
1920 QObject::connect(vect_QActions[8], SIGNAL(triggered()), view, SLOT(saveView()));
1922 vect_QActions[9] = new QAction(QIcon(":/properties-icon"), "Display properties window (CTRL+P)", this);
1923 vect_QActions[9]->setIconVisibleInMenu(true);
1924 QObject::connect(vect_QActions[9], SIGNAL(triggered()), this, SLOT(displayPropertiesWin()));
1926 if (global_control_panel->myLayout->count() == 0)
1927 vect_QActions[9]->setDisabled(true);
1931 void CvWindow::createShortcuts()
1933 vect_QShortcuts.resize(10);
1935 QWidget* view = myView->getWidget();
1937 vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this);
1938 QObject::connect(vect_QShortcuts[0], SIGNAL(activated()), view, SLOT(siftWindowOnLeft()));
1940 vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this);
1941 QObject::connect(vect_QShortcuts[1], SIGNAL(activated()), view, SLOT(siftWindowOnRight()));
1943 vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this);
1944 QObject::connect(vect_QShortcuts[2], SIGNAL(activated()), view, SLOT(siftWindowOnUp()));
1946 vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this);
1947 QObject::connect(vect_QShortcuts[3], SIGNAL(activated()), view, SLOT(siftWindowOnDown()));
1949 vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this);
1950 QObject::connect(vect_QShortcuts[4], SIGNAL(activated()), view, SLOT(resetZoom()));
1952 vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this);
1953 QObject::connect(vect_QShortcuts[5], SIGNAL(activated()), view, SLOT(imgRegion()));
1955 vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this);
1956 QObject::connect(vect_QShortcuts[6], SIGNAL(activated()), view, SLOT(ZoomIn()));
1958 vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this);
1959 QObject::connect(vect_QShortcuts[7], SIGNAL(activated()), view, SLOT(ZoomOut()));
1961 vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this);
1962 QObject::connect(vect_QShortcuts[8], SIGNAL(activated()), view, SLOT(saveView()));
1964 vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this);
1965 QObject::connect(vect_QShortcuts[9], SIGNAL(activated()), this, SLOT(displayPropertiesWin()));
1969 void CvWindow::createToolBar()
1971 myToolBar = new QToolBar(this);
1972 myToolBar->setFloatable(false); //is not a window
1973 myToolBar->setFixedHeight(28);
1974 myToolBar->setMinimumWidth(1);
1976 foreach (QAction *a, vect_QActions)
1977 myToolBar->addAction(a);
1981 void CvWindow::createStatusBar()
1983 myStatusBar = new QStatusBar(this);
1984 myStatusBar->setSizeGripEnabled(false);
1985 myStatusBar->setFixedHeight(20);
1986 myStatusBar->setMinimumWidth(1);
1987 myStatusBar_msg = new QLabel;
1989 //I comment this because if we change the style, myview (the picture)
1990 //will not be the correct size anymore (will lost 2 pixel because of the borders)
1992 //myStatusBar_msg->setFrameStyle(QFrame::Raised);
1994 myStatusBar_msg->setAlignment(Qt::AlignHCenter);
1995 myStatusBar->addWidget(myStatusBar_msg);
1999 void CvWindow::hideTools()
2005 myStatusBar->hide();
2007 if (global_control_panel)
2008 global_control_panel->hide();
2012 void CvWindow::showTools()
2018 myStatusBar->show();
2022 CvWinProperties* CvWindow::createParameterWindow()
2024 QString name_paraWindow = QFileInfo(QApplication::applicationFilePath()).fileName() + " settings";
2026 CvWinProperties* result = new CvWinProperties(name_paraWindow, guiMainThread);
2032 void CvWindow::displayPropertiesWin()
2034 if (global_control_panel->isHidden())
2035 global_control_panel->show();
2037 global_control_panel->hide();
2041 //Need more test here !
2042 void CvWindow::keyPressEvent(QKeyEvent *evnt)
2044 //see http://doc.trolltech.com/4.6/qt.html#Key-enum
2045 int key = evnt->key();
2047 Qt::Key qtkey = static_cast<Qt::Key>(key);
2048 char asciiCode = QTest::keyToAscii(qtkey);
2050 key = static_cast<int>(asciiCode);
2052 key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend
2054 //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions
2055 if (evnt->modifiers() != Qt::ControlModifier)
2060 key_pressed.wakeAll();
2064 QWidget::keyPressEvent(evnt);
2068 void CvWindow::icvLoadControlPanel()
2070 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");
2072 int bsize = settings.beginReadArray("bars");
2074 if (bsize == global_control_panel->myLayout->layout()->count())
2076 for (int i = 0; i < bsize; ++i)
2078 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2079 settings.setArrayIndex(i);
2080 if (t->type == type_CvTrackbar)
2082 if (t->name_bar == settings.value("namebar").toString())
2084 ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt());
2087 if (t->type == type_CvButtonbar)
2089 int subsize = settings.beginReadArray(QString("buttonbar")+i);
2091 if ( subsize == ((CvButtonbar*)t)->layout()->count() )
2092 icvLoadButtonbar((CvButtonbar*)t,&settings);
2094 settings.endArray();
2099 settings.endArray();
2103 void CvWindow::icvSaveControlPanel()
2105 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel");
2107 settings.beginWriteArray("bars");
2109 for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i)
2111 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2112 settings.setArrayIndex(i);
2113 if (t->type == type_CvTrackbar)
2115 settings.setValue("namebar", QString(t->name_bar));
2116 settings.setValue("valuebar",((CvTrackbar*)t)->slider->value());
2118 if (t->type == type_CvButtonbar)
2120 settings.beginWriteArray(QString("buttonbar")+i);
2121 icvSaveButtonbar((CvButtonbar*)t,&settings);
2122 settings.endArray();
2126 settings.endArray();
2130 void CvWindow::icvSaveButtonbar(CvButtonbar* b, QSettings* settings)
2132 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2134 settings->setArrayIndex(i);
2136 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2137 QString myclass(QLatin1String(temp->metaObject()->className()));
2139 if (myclass == "CvPushButton")
2141 CvPushButton* button = (CvPushButton*) temp;
2142 settings->setValue("namebutton", button->text());
2143 settings->setValue("valuebutton", int(button->isChecked()));
2145 else if (myclass == "CvCheckBox")
2147 CvCheckBox* button = (CvCheckBox*) temp;
2148 settings->setValue("namebutton", button->text());
2149 settings->setValue("valuebutton", int(button->isChecked()));
2151 else if (myclass == "CvRadioButton")
2153 CvRadioButton* button = (CvRadioButton*) temp;
2154 settings->setValue("namebutton", button->text());
2155 settings->setValue("valuebutton", int(button->isChecked()));
2161 void CvWindow::icvLoadButtonbar(CvButtonbar* b, QSettings* settings)
2163 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2165 settings->setArrayIndex(i);
2167 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2168 QString myclass(QLatin1String(temp->metaObject()->className()));
2170 if (myclass == "CvPushButton")
2172 CvPushButton* button = (CvPushButton*) temp;
2174 if (button->text() == settings->value("namebutton").toString())
2175 button->setChecked(settings->value("valuebutton").toInt());
2177 else if (myclass == "CvCheckBox")
2179 CvCheckBox* button = (CvCheckBox*) temp;
2181 if (button->text() == settings->value("namebutton").toString())
2182 button->setChecked(settings->value("valuebutton").toInt());
2184 else if (myclass == "CvRadioButton")
2186 CvRadioButton* button = (CvRadioButton*) temp;
2188 if (button->text() == settings->value("namebutton").toString())
2189 button->setChecked(settings->value("valuebutton").toInt());
2196 void CvWindow::icvLoadTrackbars(QSettings* settings)
2198 int bsize = settings->beginReadArray("trackbars");
2200 //trackbar are saved in the same order, so no need to use icvFindTrackbarByName
2202 if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)
2204 for (int i = 0; i < bsize; ++i)
2206 settings->setArrayIndex(i);
2208 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2210 if (t->name_bar == settings->value("name").toString())
2211 t->slider->setValue(settings->value("value").toInt());
2216 settings->endArray();
2220 void CvWindow::icvSaveTrackbars(QSettings* settings)
2222 settings->beginWriteArray("trackbars");
2224 for (int i = 0; i < myBarLayout->layout()->count(); ++i)
2226 settings->setArrayIndex(i);
2228 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2230 settings->setValue("name", t->name_bar);
2231 settings->setValue("value", t->slider->value());
2234 settings->endArray();
2238 //////////////////////////////////////////////////////
2242 DefaultViewPort::DefaultViewPort(CvWindow* arg, int arg2) : QGraphicsView(arg), image2Draw_mat(0)
2244 centralWidget = arg;
2245 param_keepRatio = arg2;
2247 setContentsMargins(0, 0, 0, 0);
2248 setMinimumSize(1, 1);
2249 setAlignment(Qt::AlignHCenter);
2251 setObjectName(QString::fromUtf8("graphicsView"));
2253 timerDisplay = new QTimer(this);
2254 timerDisplay->setSingleShot(true);
2255 connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo()));
2258 positionGrabbing = QPointF(0, 0);
2259 positionCorners = QRect(0, 0, size().width(), size().height());
2263 mouseCoordinate = QPoint(-1, -1);
2266 setStyleSheet( "QGraphicsView { border-style: none; }" );
2268 image2Draw_mat = cvCreateMat(viewport()->height(), viewport()->width(), CV_8UC3);
2269 cvZero(image2Draw_mat);
2271 nbChannelOriginImage = 0;
2273 setInteractive(false);
2274 setMouseTracking(true); //receive mouse event everytime
2278 DefaultViewPort::~DefaultViewPort()
2281 cvReleaseMat(&image2Draw_mat);
2285 QWidget* DefaultViewPort::getWidget()
2291 void DefaultViewPort::setMouseCallBack(CvMouseCallback m, void* param)
2295 on_mouse_param = param;
2298 void DefaultViewPort::writeSettings(QSettings& settings)
2300 settings.setValue("matrix_view.m11", param_matrixWorld.m11());
2301 settings.setValue("matrix_view.m12", param_matrixWorld.m12());
2302 settings.setValue("matrix_view.m13", param_matrixWorld.m13());
2303 settings.setValue("matrix_view.m21", param_matrixWorld.m21());
2304 settings.setValue("matrix_view.m22", param_matrixWorld.m22());
2305 settings.setValue("matrix_view.m23", param_matrixWorld.m23());
2306 settings.setValue("matrix_view.m31", param_matrixWorld.m31());
2307 settings.setValue("matrix_view.m32", param_matrixWorld.m32());
2308 settings.setValue("matrix_view.m33", param_matrixWorld.m33());
2312 void DefaultViewPort::readSettings(QSettings& settings)
2314 qreal m11 = settings.value("matrix_view.m11", param_matrixWorld.m11()).toDouble();
2315 qreal m12 = settings.value("matrix_view.m12", param_matrixWorld.m12()).toDouble();
2316 qreal m13 = settings.value("matrix_view.m13", param_matrixWorld.m13()).toDouble();
2317 qreal m21 = settings.value("matrix_view.m21", param_matrixWorld.m21()).toDouble();
2318 qreal m22 = settings.value("matrix_view.m22", param_matrixWorld.m22()).toDouble();
2319 qreal m23 = settings.value("matrix_view.m23", param_matrixWorld.m23()).toDouble();
2320 qreal m31 = settings.value("matrix_view.m31", param_matrixWorld.m31()).toDouble();
2321 qreal m32 = settings.value("matrix_view.m32", param_matrixWorld.m32()).toDouble();
2322 qreal m33 = settings.value("matrix_view.m33", param_matrixWorld.m33()).toDouble();
2324 param_matrixWorld = QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33);
2328 double DefaultViewPort::getRatio()
2330 return param_keepRatio;
2334 void DefaultViewPort::setRatio(int flags)
2336 if (getRatio() == flags) //nothing to do
2340 if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO)
2342 centralWidget->param_ratio_mode = flags;
2343 param_keepRatio = flags;
2345 viewport()->update();
2350 void DefaultViewPort::updateImage(const CvArr* arr)
2357 if (CV_IS_IMAGE_HDR(arr))
2358 origin = ((IplImage*)arr)->origin;
2360 mat = cvGetMat(arr, &stub);
2362 if (!image2Draw_mat || !CV_ARE_SIZES_EQ(image2Draw_mat, mat))
2365 cvReleaseMat(&image2Draw_mat);
2367 //the image in ipl (to do a deep copy with cvCvtColor)
2368 image2Draw_mat = cvCreateMat(mat->rows, mat->cols, CV_8UC3);
2369 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows, image2Draw_mat->step, QImage::Format_RGB888);
2371 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2372 ratioX = width() / float(image2Draw_mat->cols);
2373 ratioY = height() / float(image2Draw_mat->rows);
2377 nbChannelOriginImage = cvGetElemType(mat);
2379 cvConvertImage(mat, image2Draw_mat, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB);
2381 viewport()->update();
2385 void DefaultViewPort::startDisplayInfo(QString text, int delayms)
2387 if (timerDisplay->isActive())
2391 if (delayms > 0) timerDisplay->start(delayms);
2396 void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
2398 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2402 void DefaultViewPort::makeCurrentOpenGlContext()
2404 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2408 void DefaultViewPort::updateGl()
2410 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2414 //Note: move 2 percent of the window
2415 void DefaultViewPort::siftWindowOnLeft()
2417 float delta = 2 * width() / (100.0 * param_matrixWorld.m11());
2418 moveView(QPointF(delta, 0));
2422 //Note: move 2 percent of the window
2423 void DefaultViewPort::siftWindowOnRight()
2425 float delta = -2 * width() / (100.0 * param_matrixWorld.m11());
2426 moveView(QPointF(delta, 0));
2430 //Note: move 2 percent of the window
2431 void DefaultViewPort::siftWindowOnUp()
2433 float delta = 2 * height() / (100.0 * param_matrixWorld.m11());
2434 moveView(QPointF(0, delta));
2438 //Note: move 2 percent of the window
2439 void DefaultViewPort::siftWindowOnDown()
2441 float delta = -2 * height() / (100.0 * param_matrixWorld.m11());
2442 moveView(QPointF(0, delta));
2446 void DefaultViewPort::imgRegion()
2448 scaleView((threshold_zoom_img_region / param_matrixWorld.m11() - 1) * 5, QPointF(size().width() / 2, size().height() / 2));
2452 void DefaultViewPort::resetZoom()
2454 param_matrixWorld.reset();
2455 controlImagePosition();
2459 void DefaultViewPort::ZoomIn()
2461 scaleView(0.5, QPointF(size().width() / 2, size().height() / 2));
2465 void DefaultViewPort::ZoomOut()
2467 scaleView(-0.5, QPointF(size().width() / 2, size().height() / 2));
2471 //can save as JPG, JPEG, BMP, PNG
2472 void DefaultViewPort::saveView()
2474 QDate date_d = QDate::currentDate();
2475 QString date_s = date_d.toString("dd.MM.yyyy");
2476 QString name_s = centralWidget->windowTitle() + "_screenshot_" + date_s;
2478 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s + ".png", tr("Images (*.png *.jpg *.bmp *.jpeg)"));
2480 if (!fileName.isEmpty()) //save the picture
2482 QString extension = fileName.right(3);
2484 // Create a new pixmap to render the viewport into
2485 QPixmap viewportPixmap(viewport()->size());
2486 viewport()->render(&viewportPixmap);
2489 if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
2491 viewportPixmap.save(fileName, "PNG");
2495 if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
2497 viewportPixmap.save(fileName, "JPG");
2501 if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
2503 viewportPixmap.save(fileName, "BMP");
2507 if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
2509 viewportPixmap.save(fileName, "JPEG");
2513 CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
2518 void DefaultViewPort::contextMenuEvent(QContextMenuEvent* evnt)
2520 if (centralWidget->vect_QActions.size() > 0)
2524 foreach (QAction *a, centralWidget->vect_QActions)
2527 menu.exec(evnt->globalPos());
2532 void DefaultViewPort::resizeEvent(QResizeEvent* evnt)
2534 controlImagePosition();
2536 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2537 ratioX = width() / float(image2Draw_mat->cols);
2538 ratioY = height() / float(image2Draw_mat->rows);
2540 if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio
2542 QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2543 newSize.scale(evnt->size(), Qt::KeepAspectRatio);
2545 //imageWidth/imageHeight = newWidth/newHeight +/- epsilon
2546 //ratioX = ratioY +/- epsilon
2547 //||ratioX - ratioY|| = epsilon
2548 if (fabs(ratioX - ratioY) * 100 > ratioX) //avoid infinity loop / epsilon = 1% of ratioX
2552 //move to the middle
2553 //newSize get the delta offset to place the picture in the middle of its parent
2554 newSize = (evnt->size() - newSize) / 2;
2556 //if the toolbar is displayed, avoid drawing myview on top of it
2557 if (centralWidget->myToolBar)
2558 if(!centralWidget->myToolBar->isHidden())
2559 newSize += QSize(0, centralWidget->myToolBar->height());
2561 move(newSize.width(), newSize.height());
2565 return QGraphicsView::resizeEvent(evnt);
2569 void DefaultViewPort::wheelEvent(QWheelEvent* evnt)
2571 scaleView(evnt->delta() / 240.0, evnt->pos());
2572 viewport()->update();
2576 void DefaultViewPort::mousePressEvent(QMouseEvent* evnt)
2578 int cv_event = -1, flags = 0;
2579 QPoint pt = evnt->pos();
2581 //icvmouseHandler: pass parameters for cv_event, flags
2582 icvmouseHandler(evnt, mouse_down, cv_event, flags);
2583 icvmouseProcessing(QPointF(pt), cv_event, flags);
2585 if (param_matrixWorld.m11()>1)
2587 setCursor(Qt::ClosedHandCursor);
2588 positionGrabbing = evnt->pos();
2591 QWidget::mousePressEvent(evnt);
2595 void DefaultViewPort::mouseReleaseEvent(QMouseEvent* evnt)
2597 int cv_event = -1, flags = 0;
2598 QPoint pt = evnt->pos();
2600 //icvmouseHandler: pass parameters for cv_event, flags
2601 icvmouseHandler(evnt, mouse_up, cv_event, flags);
2602 icvmouseProcessing(QPointF(pt), cv_event, flags);
2604 if (param_matrixWorld.m11()>1)
2605 setCursor(Qt::OpenHandCursor);
2607 QWidget::mouseReleaseEvent(evnt);
2611 void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
2613 int cv_event = -1, flags = 0;
2614 QPoint pt = evnt->pos();
2616 //icvmouseHandler: pass parameters for cv_event, flags
2617 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
2618 icvmouseProcessing(QPointF(pt), cv_event, flags);
2620 QWidget::mouseDoubleClickEvent(evnt);
2624 void DefaultViewPort::mouseMoveEvent(QMouseEvent* evnt)
2626 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
2627 QPoint pt = evnt->pos();
2629 //icvmouseHandler: pass parameters for cv_event, flags
2630 icvmouseHandler(evnt, mouse_move, cv_event, flags);
2631 icvmouseProcessing(QPointF(pt), cv_event, flags);
2633 if (param_matrixWorld.m11() > 1 && evnt->buttons() == Qt::LeftButton)
2635 QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11();
2636 positionGrabbing = evnt->pos();
2640 //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp)
2641 //the status bar will only be repaint when a click occurs.
2642 if (centralWidget->myStatusBar)
2643 viewport()->update();
2645 QWidget::mouseMoveEvent(evnt);
2649 void DefaultViewPort::paintEvent(QPaintEvent* evnt)
2651 QPainter myPainter(viewport());
2652 myPainter.setWorldTransform(param_matrixWorld);
2656 //Now disable matrixWorld for overlay display
2657 myPainter.setWorldMatrixEnabled(false);
2659 //overlay pixel values if zoomed in far enough
2660 if (param_matrixWorld.m11()*ratioX >= threshold_zoom_img_region &&
2661 param_matrixWorld.m11()*ratioY >= threshold_zoom_img_region)
2663 drawImgRegion(&myPainter);
2666 //in mode zoom/panning
2667 if (param_matrixWorld.m11() > 1)
2669 drawViewOverview(&myPainter);
2672 //for information overlay
2674 drawInstructions(&myPainter);
2677 if (centralWidget->myStatusBar)
2680 QGraphicsView::paintEvent(evnt);
2684 void DefaultViewPort::stopDisplayInfo()
2686 timerDisplay->stop();
2691 inline bool DefaultViewPort::isSameSize(IplImage* img1, IplImage* img2)
2693 return img1->width == img2->width && img1->height == img2->height;
2697 void DefaultViewPort::controlImagePosition()
2699 qreal left, top, right, bottom;
2701 //after check top-left, bottom right corner to avoid getting "out" during zoom/panning
2702 param_matrixWorld.map(0,0,&left,&top);
2706 param_matrixWorld.translate(-left,0);
2711 param_matrixWorld.translate(0,-top);
2716 QSize sizeImage = size();
2717 param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom);
2718 if (right < sizeImage.width())
2720 param_matrixWorld.translate(sizeImage.width()-right,0);
2721 right = sizeImage.width();
2723 if (bottom < sizeImage.height())
2725 param_matrixWorld.translate(0,sizeImage.height()-bottom);
2726 bottom = sizeImage.height();
2729 //save corner position
2730 positionCorners.setTopLeft(QPoint(left,top));
2731 positionCorners.setBottomRight(QPoint(right,bottom));
2732 //save also the inv matrix
2733 matrixWorld_inv = param_matrixWorld.inverted();
2735 //viewport()->update();
2738 void DefaultViewPort::moveView(QPointF delta)
2740 param_matrixWorld.translate(delta.x(),delta.y());
2741 controlImagePosition();
2742 viewport()->update();
2745 //factor is -0.5 (zoom out) or 0.5 (zoom in)
2746 void DefaultViewPort::scaleView(qreal factor,QPointF center)
2748 factor/=5;//-0.1 <-> 0.1
2749 factor+=1;//0.9 <-> 1.1
2751 //limit zoom out ---
2752 if (param_matrixWorld.m11()==1 && factor < 1)
2755 if (param_matrixWorld.m11()*factor<1)
2756 factor = 1/param_matrixWorld.m11();
2759 //limit zoom int ---
2760 if (param_matrixWorld.m11()>100 && factor > 1)
2763 //inverse the transform
2765 matrixWorld_inv.map(center.x(),center.y(),&a,&b);
2767 param_matrixWorld.translate(a-factor*a,b-factor*b);
2768 param_matrixWorld.scale(factor,factor);
2770 controlImagePosition();
2773 if (centralWidget->myStatusBar)
2774 centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000);
2776 if (param_matrixWorld.m11()>1)
2777 setCursor(Qt::OpenHandCursor);
2783 //up, down, dclick, move
2784 void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)
2786 Qt::KeyboardModifiers modifiers = evnt->modifiers();
2787 Qt::MouseButtons buttons = evnt->buttons();
2790 if(modifiers & Qt::ShiftModifier)
2791 flags |= CV_EVENT_FLAG_SHIFTKEY;
2792 if(modifiers & Qt::ControlModifier)
2793 flags |= CV_EVENT_FLAG_CTRLKEY;
2794 if(modifiers & Qt::AltModifier)
2795 flags |= CV_EVENT_FLAG_ALTKEY;
2797 if(buttons & Qt::LeftButton)
2798 flags |= CV_EVENT_FLAG_LBUTTON;
2799 if(buttons & Qt::RightButton)
2800 flags |= CV_EVENT_FLAG_RBUTTON;
2801 if(buttons & Qt::MidButton)
2802 flags |= CV_EVENT_FLAG_MBUTTON;
2804 cv_event = CV_EVENT_MOUSEMOVE;
2805 switch(evnt->button())
2807 case Qt::LeftButton:
2808 cv_event = tableMouseButtons[category][0];
2809 flags |= CV_EVENT_FLAG_LBUTTON;
2811 case Qt::RightButton:
2812 cv_event = tableMouseButtons[category][1];
2813 flags |= CV_EVENT_FLAG_RBUTTON;
2816 cv_event = tableMouseButtons[category][2];
2817 flags |= CV_EVENT_FLAG_MBUTTON;
2824 void DefaultViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
2826 //to convert mouse coordinate
2828 matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy);
2830 mouseCoordinate.rx()=floor(pfx/ratioX);
2831 mouseCoordinate.ry()=floor(pfy/ratioY);
2834 on_mouse( cv_event, mouseCoordinate.x(),
2835 mouseCoordinate.y(), flags, on_mouse_param );
2839 QSize DefaultViewPort::sizeHint() const
2842 return QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2844 return QGraphicsView::sizeHint();
2848 void DefaultViewPort::draw2D(QPainter *painter)
2850 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888);
2851 painter->drawImage(QRect(0,0,viewport()->width(),viewport()->height()), image2Draw_qt, QRect(0,0, image2Draw_qt.width(), image2Draw_qt.height()) );
2854 //only if CV_8UC1 or CV_8UC3
2855 void DefaultViewPort::drawStatusBar()
2857 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2860 if (mouseCoordinate.x()>=0 &&
2861 mouseCoordinate.y()>=0 &&
2862 mouseCoordinate.x()<image2Draw_qt.width() &&
2863 mouseCoordinate.y()<image2Draw_qt.height())
2864 // if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0)
2866 QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate);
2868 if (nbChannelOriginImage==CV_8UC3 )
2870 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2871 .arg(mouseCoordinate.x())
2872 .arg(mouseCoordinate.y())+
2873 tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+
2874 tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+
2875 tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2])
2879 if (nbChannelOriginImage==CV_8UC1)
2881 //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed
2882 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2883 .arg(mouseCoordinate.x())
2884 .arg(mouseCoordinate.y())+
2885 tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue))
2891 //accept only CV_8UC1 and CV_8UC8 image for now
2892 void DefaultViewPort::drawImgRegion(QPainter *painter)
2894 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2897 double pixel_width = param_matrixWorld.m11()*ratioX;
2898 double pixel_height = param_matrixWorld.m11()*ratioY;
2900 qreal offsetX = param_matrixWorld.dx()/pixel_width;
2901 offsetX = offsetX - floor(offsetX);
2902 qreal offsetY = param_matrixWorld.dy()/pixel_height;
2903 offsetY = offsetY - floor(offsetY);
2905 QSize view = size();
2906 QVarLengthArray<QLineF, 30> linesX;
2907 for (qreal _x = offsetX*pixel_width; _x < view.width(); _x += pixel_width )
2908 linesX.append(QLineF(_x, 0, _x, view.height()));
2910 QVarLengthArray<QLineF, 30> linesY;
2911 for (qreal _y = offsetY*pixel_height; _y < view.height(); _y += pixel_height )
2912 linesY.append(QLineF(0, _y, view.width(), _y));
2915 QFont f = painter->font();
2916 int original_font_size = f.pointSize();
2918 //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2919 f.setPixelSize(10+(pixel_height-threshold_zoom_img_region)/5);
2920 painter->setFont(f);
2923 for (int j=-1;j<height()/pixel_height;j++)//-1 because display the pixels top rows left columns
2924 for (int i=-1;i<width()/pixel_width;i++)//-1
2926 // Calculate top left of the pixel's position in the viewport (screen space)
2927 QPointF pos_in_view((i+offsetX)*pixel_width, (j+offsetY)*pixel_height);
2929 // Calculate top left of the pixel's position in the image (image space)
2930 QPointF pos_in_image = matrixWorld_inv.map(pos_in_view);// Top left of pixel in view
2931 pos_in_image.rx() = pos_in_image.x()/ratioX;
2932 pos_in_image.ry() = pos_in_image.y()/ratioY;
2933 QPoint point_in_image(pos_in_image.x() + 0.5f,pos_in_image.y() + 0.5f);// Add 0.5 for rounding
2936 if (image2Draw_qt.valid(point_in_image))
2937 rgbValue = image2Draw_qt.pixel(point_in_image);
2939 rgbValue = qRgb(0,0,0);
2941 if (nbChannelOriginImage==CV_8UC3)
2945 val = tr("%1 %2").arg(point2.x()).arg(point2.y());
2946 painter->setPen(QPen(Qt::black, 1));
2947 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
2948 Qt::AlignCenter, val);
2952 val = tr("%1").arg(qRed(rgbValue));
2953 painter->setPen(QPen(Qt::red, 1));
2954 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height/3),
2955 Qt::AlignCenter, val);
2957 val = tr("%1").arg(qGreen(rgbValue));
2958 painter->setPen(QPen(Qt::green, 1));
2959 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+pixel_height/3,pixel_width,pixel_height/3),
2960 Qt::AlignCenter, val);
2962 val = tr("%1").arg(qBlue(rgbValue));
2963 painter->setPen(QPen(Qt::blue, 1));
2964 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+2*pixel_height/3,pixel_width,pixel_height/3),
2965 Qt::AlignCenter, val);
2969 if (nbChannelOriginImage==CV_8UC1)
2971 QString val = tr("%1").arg(qRed(rgbValue));
2972 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height),
2973 Qt::AlignCenter, val);
2977 painter->setPen(QPen(Qt::black, 1));
2978 painter->drawLines(linesX.data(), linesX.size());
2979 painter->drawLines(linesY.data(), linesY.size());
2982 f.setPointSize(original_font_size);
2983 painter->setFont(f);
2987 void DefaultViewPort::drawViewOverview(QPainter *painter)
2989 QSize viewSize = size();
2990 viewSize.scale ( 100, 100,Qt::KeepAspectRatio );
2992 const int margin = 5;
2994 //draw the image's location
2995 painter->setBrush(QColor(0, 0, 0, 127));
2996 painter->setPen(Qt::darkGreen);
2997 painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height()));
2999 //daw the view's location inside the image
3000 qreal ratioSize = 1/param_matrixWorld.m11();
3001 qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height());
3002 painter->setPen(Qt::darkBlue);
3003 painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin,
3004 -positionCorners.top()*ratioSize*ratioWindow,
3005 (viewSize.width()-1)*ratioSize,
3006 (viewSize.height()-1)*ratioSize)
3010 void DefaultViewPort::drawInstructions(QPainter *painter)
3012 QFontMetrics metrics = QFontMetrics(font());
3013 int border = qMax(4, metrics.leading());
3015 QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
3016 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3017 painter->setRenderHint(QPainter::TextAntialiasing);
3018 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3019 QColor(0, 0, 0, 127));
3020 painter->setPen(Qt::white);
3021 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3022 QColor(0, 0, 0, 127));
3024 painter->drawText((width() - qrect.width())/2, border,
3025 qrect.width(), qrect.height(),
3026 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3030 void DefaultViewPort::setSize(QSize /*size_*/)
3035 //////////////////////////////////////////////////////
3038 #ifdef HAVE_QT_OPENGL
3040 OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)
3049 OpenGlViewPort::~OpenGlViewPort()
3053 QWidget* OpenGlViewPort::getWidget()
3058 void OpenGlViewPort::setMouseCallBack(CvMouseCallback callback, void* param)
3060 mouseCallback = callback;
3064 void OpenGlViewPort::writeSettings(QSettings& /*settings*/)
3068 void OpenGlViewPort::readSettings(QSettings& /*settings*/)
3072 double OpenGlViewPort::getRatio()
3074 return (double)width() / height();
3077 void OpenGlViewPort::setRatio(int /*flags*/)
3081 void OpenGlViewPort::updateImage(const CvArr* /*arr*/)
3085 void OpenGlViewPort::startDisplayInfo(QString /*text*/, int /*delayms*/)
3089 void OpenGlViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
3091 glDrawCallback = callback;
3092 glDrawData = userdata;
3095 void OpenGlViewPort::makeCurrentOpenGlContext()
3100 void OpenGlViewPort::updateGl()
3102 QGLWidget::updateGL();
3105 void OpenGlViewPort::initializeGL()
3107 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3110 void OpenGlViewPort::resizeGL(int w, int h)
3112 glViewport(0, 0, w, h);
3115 void OpenGlViewPort::paintGL()
3117 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3120 glDrawCallback(glDrawData);
3123 void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)
3125 int cv_event = -1, flags = 0;
3126 QPoint pt = evnt->pos();
3128 icvmouseHandler(evnt, mouse_down, cv_event, flags);
3129 icvmouseProcessing(QPointF(pt), cv_event, flags);
3131 QGLWidget::mousePressEvent(evnt);
3135 void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)
3137 int cv_event = -1, flags = 0;
3138 QPoint pt = evnt->pos();
3140 icvmouseHandler(evnt, mouse_up, cv_event, flags);
3141 icvmouseProcessing(QPointF(pt), cv_event, flags);
3143 QGLWidget::mouseReleaseEvent(evnt);
3147 void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
3149 int cv_event = -1, flags = 0;
3150 QPoint pt = evnt->pos();
3152 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
3153 icvmouseProcessing(QPointF(pt), cv_event, flags);
3155 QGLWidget::mouseDoubleClickEvent(evnt);
3159 void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)
3161 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
3162 QPoint pt = evnt->pos();
3164 //icvmouseHandler: pass parameters for cv_event, flags
3165 icvmouseHandler(evnt, mouse_move, cv_event, flags);
3166 icvmouseProcessing(QPointF(pt), cv_event, flags);
3168 QGLWidget::mouseMoveEvent(evnt);
3171 void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)
3173 Qt::KeyboardModifiers modifiers = evnt->modifiers();
3174 Qt::MouseButtons buttons = evnt->buttons();
3177 if (modifiers & Qt::ShiftModifier)
3178 flags |= CV_EVENT_FLAG_SHIFTKEY;
3179 if (modifiers & Qt::ControlModifier)
3180 flags |= CV_EVENT_FLAG_CTRLKEY;
3181 if (modifiers & Qt::AltModifier)
3182 flags |= CV_EVENT_FLAG_ALTKEY;
3184 if (buttons & Qt::LeftButton)
3185 flags |= CV_EVENT_FLAG_LBUTTON;
3186 if (buttons & Qt::RightButton)
3187 flags |= CV_EVENT_FLAG_RBUTTON;
3188 if (buttons & Qt::MidButton)
3189 flags |= CV_EVENT_FLAG_MBUTTON;
3191 cv_event = CV_EVENT_MOUSEMOVE;
3192 switch (evnt->button())
3194 case Qt::LeftButton:
3195 cv_event = tableMouseButtons[category][0];
3196 flags |= CV_EVENT_FLAG_LBUTTON;
3199 case Qt::RightButton:
3200 cv_event = tableMouseButtons[category][1];
3201 flags |= CV_EVENT_FLAG_RBUTTON;
3205 cv_event = tableMouseButtons[category][2];
3206 flags |= CV_EVENT_FLAG_MBUTTON;
3215 void OpenGlViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
3218 mouseCallback(cv_event, pt.x(), pt.y(), flags, mouseData);
3222 QSize OpenGlViewPort::sizeHint() const
3224 if (size.width() > 0 && size.height() > 0)
3227 return QGLWidget::sizeHint();
3230 void OpenGlViewPort::setSize(QSize size_)