MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); qDebug()<<"Begin Program\n"; QFontDatabase fontDB; fontDB.addApplicationFont(":/Fonts/CMR_Regular.ttf"); fontDB.addApplicationFont(":/Fonts/CMR_Bold.ttf"); fontDB.addApplicationFont(":/Fonts/CMR_Italic.ttf"); fontDB.addApplicationFont(":/Fonts/CMR_BoldItalic.ttf"); QFont CMRFont = QFont("Computer Modern Roman"); QApplication::setFont(CMRFont); //Create the central widget where the other frames will be inserted QWidget *wdgMain = new QWidget(this); qDebug()<<"Widget Initaited"; setCentralWidget(wdgMain); //Create the outermost Layout to divide between the table, the preview and the buttons //QGridLayout *mainLayout = new QGridLayout; QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->setSpacing(10); mainLayout->setContentsMargins(15,5,15,10); //The frame for the buttons is created and the ADD Record REMOVE Record and MODIFY Button are added in a QHBOX QFrame *frmButtons = new QFrame(); frmButtons->setFrameStyle(QFrame::Box | QFrame::Raised); frmButtons->setLineWidth(1); //QPushButton *btnAddRecord = new QPushButton("AddRecord",frmButtons); btnAddRecord->setEnabled(false); //QPushButton *btnRemoveRecord = new QPushButton("Remove Record",frmButtons); btnRemoveRecord->setEnabled(false); //QPushButton *btnModifyRecord = new QPushButton("Modify Record",frmButtons); btnModifyRecord->setEnabled(false); //QPushButton *btnPrint = new QPushButton("Export",frmButtons); btnPrint->setEnabled(false); QHBoxLayout *btnLayout = new QHBoxLayout; btnLayout->addWidget(btnAddRecord); btnLayout->addWidget(btnRemoveRecord); btnLayout->addWidget(btnModifyRecord); btnLayout->addWidget(btnPrint); frmButtons->setLayout(btnLayout); //The frame for the preview is created frmPreview->setLayout(prwLayout); //The Table viewer is created without grid and is added to the main layout dbTableView=new QTableView(this); dbTableView->setShowGrid(false); dbTableView->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::MinimumExpanding); //mainLayout->addWidget(dbTableView,0,0,5,4); //The left frame is created and the table and button frames are added QVBoxLayout *lftLayout = new QVBoxLayout; lftLayout->addWidget(dbTableView); lftLayout->addWidget(frmButtons); //The main layout is created by adding the left layout and the preview widget mainLayout->addLayout(lftLayout); mainLayout->addWidget(scrPreview); //A value is given to the database and a connetion is made using the custom CreatConnection //dbName="/Users/Castro/Documents/Svago/Programmazione/Qt/database/movies.sqlite"; //CreateConnection(dbName); //Go to method, return bool //QSqlQuery querytest (q.createUpdate("Main_table",Update,Where),db); //Ther preview frame is populated with the labeled text //preview field is enabeled in order to navigate throught he preview fields array //The scroll area is set to a fixed width wich allowes to view the whole contents without scrolling to the side frmPreview->setMinimumWidth(prwLayout->sizeHint().width()); scrPreview->setWidget(frmPreview); scrPreview->setFixedWidth(frmPreview->width()+20); wdgMain->setLayout(mainLayout); wdgMain->show(); createActions(); createMenu(); //The table view signal "current changed" is connected to the slot which changes the selected record //connect(dbTableView->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)), //SLOT(currentSelectionChanged(const QModelIndex &))); connect(dbTableView,SIGNAL(doubleClicked(QModelIndex)),SLOT(recordDoubleClicked(const QModelIndex))); connect(dbmodel, SIGNAL(modelReset()), this, SLOT(modelHasReset())); connect(dbmodel, SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)), this, SLOT(dataChangeEmitted())); //connect(dbmodel,SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInsertedEmitted(QModelIndex,int,int))); connect(btnAddRecord,SIGNAL(clicked()),SLOT(createNewRecord())); connect(btnRemoveRecord,SIGNAL(clicked()),SLOT(deleteRecord())); connect(btnModifyRecord,SIGNAL(clicked()),SLOT(updateRecord())); connect(btnPrint,SIGNAL(clicked()),this,SLOT(printRecord())); QDesktopWidget dw; QRect dwRect = dw.availableGeometry(this); //dw.availablegeometry(this); resize(dwRect.size()*0.7); //QRect mwRect = this->geometry(); move(0.15*dwRect.width(),0.15*dwRect.height()); }
bool EventFilter::eventFilter(QObject *watched, QEvent *event) { Q_UNUSED(watched); AVPlayer *player = static_cast<AVPlayer*>(parent()); if (!player || !player->renderer() || !player->renderer()->widget()) return false; if (qobject_cast<QWidget*>(watched) != player->renderer()->widget()) { return false; } #ifndef QT_NO_DYNAMIC_CAST //dynamic_cast is defined as a macro to force a compile error if (player->renderer() != dynamic_cast<VideoRenderer*>(watched)) { // return false; } #endif QEvent::Type type = event->type(); switch (type) { case QEvent::KeyPress: { QKeyEvent *key_event = static_cast<QKeyEvent*>(event); int key = key_event->key(); Qt::KeyboardModifiers modifiers = key_event->modifiers(); switch (key) { case Qt::Key_C: //capture player->captureVideo(); break; case Qt::Key_N: //check playing? player->playNextFrame(); break; case Qt::Key_P: player->play(); break; case Qt::Key_Q: case Qt::Key_Escape: qApp->quit(); break; case Qt::Key_S: player->stop(); //check playing? break; case Qt::Key_Space: //check playing? qDebug("isPaused = %d", player->isPaused()); player->pause(!player->isPaused()); break; case Qt::Key_F: { //TODO: move to gui QWidget *w = qApp->activeWindow(); if (!w) return false; if (w->isFullScreen()) w->showNormal(); else w->showFullScreen(); } break; case Qt::Key_Up: { AudioOutput *ao = player->audio(); if (modifiers == Qt::ControlModifier) { qreal s = player->speed(); if (s < 1.4) s += 0.02; else s += 0.05; if (qAbs<qreal>(s-1.0) <= 0.01) s = 1.0; player->setSpeed(s); return true; } if (ao && ao->isAvailable()) { qreal v = player->audio()->volume(); if (v > 0.5) v += 0.1; else if (v > 0.1) v += 0.05; else v += 0.025; player->audio()->setVolume(v); qDebug("vol = %.3f", player->audio()->volume()); } } break; case Qt::Key_Down: { AudioOutput *ao = player->audio(); if (modifiers == Qt::ControlModifier) { qreal s = player->speed(); if (s < 1.4) s -= 0.02; else s -= 0.05; if (qAbs<qreal>(s-1.0) <= 0.01) s = 1.0; s = qMax<qreal>(s, 0.0); player->setSpeed(s); return true; } if (ao && ao->isAvailable()) { qreal v = player->audio()->volume(); if (v > 0.5) v -= 0.1; else if (v > 0.1) v -= 0.05; else v -= 0.025; player->audio()->setVolume(v); qDebug("vol = %.3f", player->audio()->volume()); } } break; case Qt::Key_O: { if (modifiers == Qt::ControlModifier) { //TODO: emit a signal so we can use custome dialogs? openLocalFile(); } else/* if (m == Qt::NoModifier) */{ emit showNextOSD(); } } break; case Qt::Key_Left: qDebug("<-"); player->seekBackward(); break; case Qt::Key_Right: qDebug("->"); player->seekForward(); break; case Qt::Key_M: if (player->audio()) { player->audio()->setMute(!player->audio()->isMute()); } break; case Qt::Key_R: { VideoRenderer* renderer = player->renderer(); VideoRenderer::OutAspectRatioMode r = renderer->outAspectRatioMode(); renderer->setOutAspectRatioMode(VideoRenderer::OutAspectRatioMode(((int)r+1)%2)); } break; case Qt::Key_T: { QWidget *w = qApp->activeWindow(); if (!w) return false; Qt::WindowFlags wf = w->windowFlags(); if (wf & Qt::WindowStaysOnTopHint) { qDebug("Window not stays on top"); w->setWindowFlags(wf & ~Qt::WindowStaysOnTopHint); } else { qDebug("Window stays on top"); w->setWindowFlags(wf | Qt::WindowStaysOnTopHint); } //call setParent() when changing the flags, causing the widget to be hidden w->show(); } break; case Qt::Key_F1: help(); break; default: return false; } break; } case QEvent::DragEnter: case QEvent::DragMove: { QDropEvent *e = static_cast<QDropEvent*>(event); e->acceptProposedAction(); } break; case QEvent::Drop: { QDropEvent *e = static_cast<QDropEvent*>(event); QString path = e->mimeData()->urls().first().toLocalFile(); player->stop(); player->load(path); player->play(); e->acceptProposedAction(); } break; case QEvent::GraphicsSceneContextMenu: { QGraphicsSceneContextMenuEvent *e = static_cast<QGraphicsSceneContextMenuEvent*>(event); showMenu(e->screenPos()); } break; case QEvent::ContextMenu: { QContextMenuEvent *e = static_cast<QContextMenuEvent*>(event); showMenu(e->globalPos()); } break; default: return false; } return true; //false: for text input }
int window_show_(egx_wnd_t hwnd) { QWidget *gwindow = (QWidget*)(hwnd); gwindow->show(); return 0; }
// NOTE: The X11 version of createSurface will re-create the native drawable if it's visual doesn't // match the one for the passed in EGLConfig EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig config, const QEglProperties *unusedProperties) { Q_UNUSED(unusedProperties); int devType = device->devType(); if (devType == QInternal::Pbuffer) { // TODO return EGL_NO_SURFACE; } QX11PixmapData *x11PixmapData = 0; if (devType == QInternal::Pixmap) { QPixmapData *pmd = static_cast<QPixmap*>(device)->data_ptr().data(); if (pmd->classId() == QPixmapData::X11Class) x11PixmapData = static_cast<QX11PixmapData*>(pmd); else { // TODO: Replace the pixmap's data with a new QX11PixmapData qWarning("WARNING: Creating an EGL surface on a QPixmap is only supported for QX11PixmapData"); return EGL_NO_SURFACE; } } else if ((devType != QInternal::Widget) && (devType != QInternal::Pbuffer)) { qWarning("WARNING: Creating an EGLSurface for device type %d isn't supported", devType); return EGL_NO_SURFACE; } VisualID visualId = QEgl::getCompatibleVisualId(config); EGLint alphaSize; eglGetConfigAttrib(QEgl::display(), config, EGL_ALPHA_SIZE, &alphaSize); if (devType == QInternal::Widget) { QWidget *widget = static_cast<QWidget*>(device); VisualID currentVisualId = 0; if (widget->testAttribute(Qt::WA_WState_Created)) currentVisualId = XVisualIDFromVisual((Visual*)widget->x11Info().visual()); if (currentVisualId != visualId) { // The window is either not created or has the wrong visual. Either way, we need // to create a window with the correct visual and call create() on the widget: bool visible = widget->isVisible(); if (visible) widget->hide(); XVisualInfo visualInfo; visualInfo.visualid = visualId; { XVisualInfo *visualInfoPtr; int matchingCount = 0; visualInfoPtr = XGetVisualInfo(widget->x11Info().display(), VisualIDMask, &visualInfo, &matchingCount); Q_ASSERT(visualInfoPtr); // visualId really should be valid! visualInfo = *visualInfoPtr; XFree(visualInfoPtr); } Window parentWindow = RootWindow(widget->x11Info().display(), widget->x11Info().screen()); if (widget->parentWidget()) parentWindow = widget->parentWidget()->winId(); XSetWindowAttributes windowAttribs; QColormap colmap = QColormap::instance(widget->x11Info().screen()); windowAttribs.background_pixel = colmap.pixel(widget->palette().color(widget->backgroundRole())); windowAttribs.border_pixel = colmap.pixel(Qt::black); unsigned int valueMask = CWBackPixel|CWBorderPixel; if (alphaSize > 0) { windowAttribs.colormap = XCreateColormap(widget->x11Info().display(), parentWindow, visualInfo.visual, AllocNone); valueMask |= CWColormap; } Window window = XCreateWindow(widget->x11Info().display(), parentWindow, widget->x(), widget->y(), widget->width(), widget->height(), 0, visualInfo.depth, InputOutput, visualInfo.visual, valueMask, &windowAttribs); // This is a nasty hack to get round the fact that we can't be a friend of QWidget: qt_set_winid_on_widget(widget, window); if (visible) widget->show(); } // At this point, the widget's window should be created and have the correct visual. Now we // just need to create the EGL surface for it: EGLSurface surf = eglCreateWindowSurface(QEgl::display(), config, (EGLNativeWindowType)widget->winId(), 0); if (surf == EGL_NO_SURFACE) qWarning("QEglContext::createSurface(): Unable to create EGL surface, error = 0x%x", eglGetError()); return surf; } if (x11PixmapData) { // X11 Pixmaps are only created with a depth, so that's all we need to check EGLint configDepth; eglGetConfigAttrib(QEgl::display(), config, EGL_BUFFER_SIZE , &configDepth); if (x11PixmapData->depth() != configDepth) { // The bit depths are wrong which means the EGLConfig isn't compatable with // this pixmap. So we need to replace the pixmap's existing data with a new // one which is created with the correct depth: #ifndef QT_NO_XRENDER if (configDepth == 32) { qWarning("Warning: EGLConfig's depth (32) != pixmap's depth (%d), converting to ARGB32", x11PixmapData->depth()); x11PixmapData->convertToARGB32(true); } else #endif { qWarning("Warning: EGLConfig's depth (%d) != pixmap's depth (%d)", configDepth, x11PixmapData->depth()); } } QEglProperties surfaceAttribs; // If the pixmap can't be bound to a texture, it's pretty useless surfaceAttribs.setValue(EGL_TEXTURE_TARGET, EGL_TEXTURE_2D); if (alphaSize > 0) surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA); else surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGB); EGLSurface surf = eglCreatePixmapSurface(QEgl::display(), config, (EGLNativePixmapType) x11PixmapData->handle(), surfaceAttribs.properties()); x11PixmapData->gl_surface = (void*)surf; QImagePixmapCleanupHooks::enableCleanupHooks(x11PixmapData); return surf; } return EGL_NO_SURFACE; }
void JabberSearch::addWidget(JabberAgentInfo *data) { QWidget *widget = NULL; bool bJoin = false; if (data->Type){ if (!strcmp(data->Type, "x")){ m_bXData = true; }else if (!strcmp(data->Type, "text-single")){ widget = new QLineEdit(this, data->Field); connect(widget, SIGNAL(returnPressed()), m_receiver, SLOT(search())); connect(widget, SIGNAL(textChanged(const QString&)), m_receiver, SLOT(textChanged(const QString&))); }else if (!strcmp(data->Type, "fixed") || !strcmp(data->Type, "instructions")){ if (data->Value){ QString text = i18(data->Value); text = text.replace(QRegExp(" +"), "\n"); QLabel *label = new QLabel(text, this); label->setAlignment(WordBreak); widget = label; bJoin = true; } }else if (!strcmp(data->Type, "list-single")){ CComboBox *box = new CComboBox(this, data->Field); for (unsigned i = 0; i < data->nOptions; i++){ const char *label = get_str(data->OptionLabels, i); const char *val = get_str(data->Options, i); if (label && val) box->addItem(i18(label), val); } widget = box; }else if (!strcmp(data->Type, "key")){ if (data->Value) m_key = data->Value; }else if (!strcmp(data->Type, "password")){ widget = new QLineEdit(this, "password"); static_cast<QLineEdit*>(widget)->setEchoMode(QLineEdit::Password); connect(widget, SIGNAL(returnPressed()), m_receiver, SLOT(search())); connect(widget, SIGNAL(textChanged(const QString&)), m_receiver, SLOT(textChanged(const QString&))); set_str(&data->Label, "Password"); }else if (!strcmp(data->Type, "online")){ widget = new QCheckBox(this, "online"); static_cast<QCheckBox*>(widget)->setText(i18n("Online only")); bJoin = true; }else if (!strcmp(data->Type, "sex")){ CComboBox *box = new CComboBox(this, data->Field); box->addItem("", "0"); box->addItem(i18n("Male"), "1"); box->addItem(i18n("Female"), "2"); set_str(&data->Label, I18N_NOOP("Gender")); widget = box; }else{ defFlds *f; for (f = fields; f->tag; f++) if (!strcmp(data->Type, f->tag)) break; if (f->tag){ widget = new QLineEdit(this, f->tag); connect(widget, SIGNAL(returnPressed()), m_receiver, SLOT(search())); connect(widget, SIGNAL(textChanged(const QString&)), m_receiver, SLOT(textChanged(const QString&))); set_str(&data->Label, f->name); }else if (data->Label){ widget = new QLineEdit(this, f->tag); connect(widget, SIGNAL(returnPressed()), m_receiver, SLOT(search())); connect(widget, SIGNAL(textChanged(const QString&)), m_receiver, SLOT(textChanged(const QString&))); } } } if (widget){ if (data->bRequired) m_required.push_back(widget); if (bJoin){ lay->addMultiCellWidget(widget, m_nPos, m_nPos, 0, 1); }else{ lay->addWidget(widget, m_nPos, 1); if (data->Label){ QLabel *label = new QLabel(i18(data->Label), this); label->setAlignment(AlignRight); lay->addWidget(label, m_nPos, 0); label->show(); } } widget->show(); m_nPos++; m_bDirty = true; QTimer::singleShot(0, this, SLOT(setSize())); } }
void VCXYPad_Test::saveXML() { QWidget w; VCXYPad pad(&w, m_doc); pad.show(); w.show(); pad.setCaption("MyPad"); pad.resize(QSize(150, 200)); pad.move(QPoint(10, 20)); pad.m_area->setPosition(QPointF(23, 45)); pad.setInputSource(new QLCInputSource(0, 1), VCXYPad::panInputSourceId); pad.setInputSource(new QLCInputSource(2, 3), VCXYPad::tiltInputSourceId); QCOMPARE(pad.m_area->position(), QPointF(23, 45)); QCOMPARE(pad.m_area->position(), QPointF(23, 45)); VCXYPadFixture fixture1(m_doc); fixture1.setHead(GroupHead(11, 0)); pad.appendFixture(fixture1); VCXYPadFixture fixture2(m_doc); fixture2.setHead(GroupHead(22, 0)); pad.appendFixture(fixture2); QDomDocument xmldoc; QDomElement root = xmldoc.createElement("Root"); xmldoc.appendChild(root); int fixture = 0, position = 0, wstate = 0, appearance = 0, pan = 0, tilt = 0; QVERIFY(pad.saveXML(&xmldoc, &root) == true); QDomNode node = root.firstChild(); QCOMPARE(node.toElement().tagName(), QString("XYPad")); QCOMPARE(node.toElement().attribute("Caption"), QString("MyPad")); node = node.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == "Fixture") { fixture++; QVERIFY(tag.attribute("ID") == QString("11") || tag.attribute("ID") == QString("22")); QVERIFY(tag.attribute("Head") == QString("0")); QCOMPARE(tag.childNodes().count(), 2); } else if (tag.tagName() == "Position") { position++; QFAIL("Legacy tag found in saved XML!"); } else if (tag.tagName() == "Pan") { pan++; QCOMPARE(tag.attribute("Position"), QString("23")); QCOMPARE(tag.firstChild().toElement().attribute("Universe"), QString("0")); QCOMPARE(tag.firstChild().toElement().attribute("Channel"), QString("1")); } else if (tag.tagName() == "Tilt") { tilt++; QCOMPARE(tag.attribute("Position"), QString("45")); QCOMPARE(tag.firstChild().toElement().attribute("Universe"), QString("2")); QCOMPARE(tag.firstChild().toElement().attribute("Channel"), QString("3")); } else if (tag.tagName() == "WindowState") { wstate++; } else if (tag.tagName() == "Appearance") { appearance++; } else { QFAIL(QString("Unexpected tag: %1").arg(tag.tagName()).toUtf8().constData()); } node = node.nextSibling(); } QCOMPARE(fixture, 2); QCOMPARE(position, 0); QCOMPARE(pan, 1); QCOMPARE(tilt, 1); QCOMPARE(wstate, 1); QCOMPARE(appearance, 1); }
int main(int argc, char **argv) { float pointSize; float pointStep; float normalLenght; float normalStep; float alphaColor; int initialSensorOffset; string filename; // Input parameters handling. g2o::CommandArgs arg; arg.param("pointSize", pointSize, 1.0f, "Size of the points"); arg.param("normalLenght", normalLenght, 0, "Lenght of the normals"); arg.param("alpha", alphaColor, 1.0f, "Alpha channel for points"); arg.param("pointStep", pointStep, 1, "Step of the points"); arg.param("normalStep", normalStep, 1, "Step of the normals"); arg.param("initialSensorOffset", initialSensorOffset, 0, "Choose if use the initial sensor offset"); arg.paramLeftOver("filename", filename, "", "Input depth image or .pwn file", true); // Set parser input. arg.parseArgs(argc, argv); Isometry3f sensorOffsetInit = Isometry3f::Identity(); if(initialSensorOffset) { sensorOffsetInit.translation() = Vector3f(0.15f, 0.0f, 0.05f); Quaternionf quaternion = Quaternionf(0.5f, -0.5f, 0.5f, -0.5f); sensorOffsetInit.linear() = quaternion.toRotationMatrix(); } sensorOffsetInit.matrix().row(3) << 0.0f, 0.0f, 0.0f, 1.0f; // Windows name static const char CALIBRATE_WINDOW[] = "Calibrate Window"; // Calibration angles int maxTrackBarValue = 1800; int alpha = maxTrackBarValue / 2; // Around x int beta = maxTrackBarValue / 2; // Around y int theta = maxTrackBarValue / 2; // Around z // Create the window and the trackbars cv::namedWindow(CALIBRATE_WINDOW); cvMoveWindow(CALIBRATE_WINDOW, 0, 0); cvResizeWindow(CALIBRATE_WINDOW, 500, 200); cvCreateTrackbar("Calibrate X", CALIBRATE_WINDOW, &alpha, 1800, NULL); cvCreateTrackbar("Calibrate Y", CALIBRATE_WINDOW, &beta, 1800, NULL); cvCreateTrackbar("Calibrate Z", CALIBRATE_WINDOW, &theta, 1800, NULL); // Create objects in order to read the input depth image / pwn file Eigen::Matrix3f cameraMatrix; cameraMatrix << 525.0f, 0.0f, 319.5f, 0.0f, 525.0f, 239.5f, 0.0f, 0.0f, 1.0f; string extension; extension = filename.substr(filename.rfind(".") + 1); Frame frame; Isometry3f globalT = Isometry3f::Identity(); cerr << "Loading " << filename.c_str() << endl; if(extension == "pgm") { PinholePointProjector projector; projector.setCameraMatrix(cameraMatrix); StatsCalculator statsCalculator; PointInformationMatrixCalculator pointInformationMatrixCalculator; NormalInformationMatrixCalculator normalInformationMatrixCalculator; DepthImageConverter depthImageConverter(&projector, &statsCalculator, &pointInformationMatrixCalculator, &normalInformationMatrixCalculator); DepthImage inputImage; inputImage.load(filename.c_str(),true); cerr << "Computing stats... "; depthImageConverter.compute(frame, inputImage); cerr << " done" << endl; } else if(extension == "pwn") { frame.load(globalT, filename.c_str()); } else { cerr << "File extension nor recognized, quitting." << endl; return(0); } Isometry3f oldSensorOffset = Isometry3f::Identity(); oldSensorOffset.matrix().row(3) << 0.0f, 0.0f, 0.0f, 1.0f; QApplication application(argc,argv); QWidget* mainWindow = new QWidget(); mainWindow->setWindowTitle("pwn_calibration"); QHBoxLayout* hlayout = new QHBoxLayout(); mainWindow->setLayout(hlayout); QVBoxLayout* vlayout = new QVBoxLayout(); hlayout->addItem(vlayout); PWNQGLViewer* viewer = new PWNQGLViewer(mainWindow); vlayout->addWidget(viewer); viewer->init(); viewer->show(); viewer->setAxisIsDrawn(true); mainWindow->show(); GLParameterPoints *pointsParams = new GLParameterPoints(pointSize, Eigen::Vector4f(1.0f, 0.0f, 0.0f, 1.0f)); pointsParams->setStep(pointStep); DrawablePoints *drawablePoints = new DrawablePoints(oldSensorOffset, pointsParams, &frame.points(), &frame.normals()); viewer->addDrawable(drawablePoints); GLParameterNormals *normalParams = new GLParameterNormals(pointSize, Eigen::Vector4f(0.0f, 0.0f, 1.0f, alphaColor), normalLenght); DrawableNormals *drawableNormals = new DrawableNormals(oldSensorOffset, normalParams, &frame.points(), &frame.normals()); normalParams->setStep(normalStep); normalParams->setNormalLength(normalLenght); viewer->addDrawable(drawableNormals); // Keep cycling Isometry3f sensorOffset; while(mainWindow->isVisible()) { // Updating variables float alphar = 2.0f * 3.14*((float)alpha - maxTrackBarValue / 2) / maxTrackBarValue; float betar = 2.0f * 3.14*((float)beta - maxTrackBarValue / 2) / maxTrackBarValue; float thetar = 2.0f * 3.14*((float)theta - maxTrackBarValue / 2) / maxTrackBarValue; // Generate rotations Quaternion<float> qx, qy, qz; qx = AngleAxis<float>(alphar, Vector3f(1.0f, 0.0f, 0.0f)); qy = AngleAxis<float>(betar, Vector3f(0.0f, 1.0f, 0.0f)); qz = AngleAxis<float>(thetar, Vector3f(0.0f, 0.0f, 1.0f)); Matrix3f totalRotation = qz.toRotationMatrix() * qy.toRotationMatrix() * qx.toRotationMatrix(); sensorOffset = Isometry3f::Identity(); sensorOffset.translation() = Vector3f(0.0f, 0.0f, 0.0f); sensorOffset.linear() = totalRotation * sensorOffsetInit.linear(); sensorOffset.matrix().row(3) << 0.0f, 0.0f, 0.0f, 1.0f; drawablePoints->setTransformation(sensorOffset); drawableNormals->setTransformation(sensorOffset); oldSensorOffset = sensorOffset; viewer->updateGL(); application.processEvents(); cv::waitKey(33); } ofstream os("sensorOffset.txt"); Vector6f offset = t2v(sensorOffset); os << offset[0] << " " << offset[1] << " " << offset[2] << " " << offset[3] << " " << offset[4] << " " << offset[5] << endl; return(0); }
/*! * \brief ItiOtbRgbaImageViewer::disassembleWidgets */ void ItiOtbRgbaImageViewer::disassembleWidgets(){ //! m_vmode = VMODE_SPLITTED; //! remove the widget m_pMainLayout->removeWidget(m_pSplitter); //! reset observer mechanism resetObserverMechanism(); //! Due to a lack of removing added itmes functionality on a QSplitter instance //! the added widgets must be firstly hidden and then deleted.. m_pItiOtbRgbaImageWidgetFullView->hide(); m_pItiOtbRgbaImageWidgetScroll->hide(); m_pItiOtbRgbaImageWidgetZoomable->hide(); delete m_pItiOtbRgbaImageWidgetFullView; delete m_pItiOtbRgbaImageWidgetScroll; delete m_pItiOtbRgbaImageWidgetZoomable; //! create the views //! scrollable view m_pItiOtbRgbaImageWidgetScroll = new ItiOtbRgbaQGLWidgetScrollable(this); m_pItiOtbRgbaImageWidgetScroll->setWindowTitle(m_pLabelScrollableResolution->text()); //! full view m_pItiOtbRgbaImageWidgetFullView = new ItiOtbRgbaQGLWidgetFullView(this); m_pItiOtbRgbaImageWidgetFullView->setWindowTitle(m_pLabelFullView->text()); //! zoomable view m_pItiOtbRgbaImageWidgetZoomable = new ItiOtbRgbaQGLWidgetZoomable(this); m_pItiOtbRgbaImageWidgetZoomable->setWindowTitle(m_pLabelZoomView->text()); //! pixel info view m_pItiViewerPixelInfoWidget = new ItiViewerPixelInfoWidget(this); m_pItiViewerPixelInfoWidget->setWindowTitle(m_pItiViewerPixelInfoWidget->title()); m_pItiViewerPixelInfoWidget->setWindowFlags(Qt::Window); m_pItiViewerPixelInfoWidget->setGeometry(QApplication::desktop()->width()/2 - 80,QApplication::desktop()->height()/2 - 80,200,200); //! //! Because of a bug causing crashes when the viewer was set in split mode, we create container widgets for each seperate view //! //! setup the zoom viewe QWidget *phelperWidgetScroll = new QWidget(this,Qt::Window); phelperWidgetScroll->setWindowTitle(m_pLabelScrollableResolution->text()); phelperWidgetScroll->setMinimumSize(QSize(150,150)); phelperWidgetScroll->setGeometry(QApplication::desktop()->width()/2 - 200,QApplication::desktop()->height()/2 - 200,200,200); QVBoxLayout *vboxLayout = new QVBoxLayout(); vboxLayout->addWidget(m_pItiOtbRgbaImageWidgetScroll); phelperWidgetScroll->setLayout(vboxLayout); //! setup the full viewe QWidget *phelperWidgetFullView = new QWidget(this,Qt::Window); phelperWidgetFullView->setMinimumSize(QSize(150,150)); phelperWidgetFullView->setWindowTitle(m_pLabelFullView->text()); phelperWidgetFullView->setGeometry(QApplication::desktop()->width()/2 - 160,QApplication::desktop()->height()/2 - 160,200,200); QVBoxLayout *vboxLayout1 = new QVBoxLayout(); vboxLayout1->addWidget(m_pItiOtbRgbaImageWidgetFullView); phelperWidgetFullView->setLayout(vboxLayout1); //! setup the zoom viewe QWidget *phelperWidgetZoomView = new QWidget(this,Qt::Window); phelperWidgetZoomView->setMinimumSize(QSize(150,150)); phelperWidgetZoomView->setWindowTitle(m_pLabelZoomView->text()); phelperWidgetZoomView->setGeometry(QApplication::desktop()->width()/2 - 120,QApplication::desktop()->height()/2 - 120,200,200); QVBoxLayout *vboxLayout2 = new QVBoxLayout(); vboxLayout2->addWidget(m_pItiOtbRgbaImageWidgetZoomable); phelperWidgetZoomView->setLayout(vboxLayout2); //! establish signals and slot connections setupConnections(); //! setup the observer mechanism setupObserverMechanism(); //! show the widgets phelperWidgetScroll->show(); phelperWidgetFullView->show(); phelperWidgetZoomView->show(); m_pItiViewerPixelInfoWidget->show(); }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(guiclient); QString username; QString databaseURL; QString passwd; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; bool haveEnhancedAuth= false; bool _enhancedAuth = false; bool haveRequireSSL = false; bool _requireSSL = false; bool havePasswd = false; QApplication app(argc, argv); #if QT_VERSION >= 0x040400 // This is the correct place for this call but on versions less // than 4.4 it causes a crash for an unknown reason so it is // called later on earlier versions. QCoreApplication::addLibraryPath(QString(".")); #endif #ifndef Q_WS_MACX QApplication::setWindowIcon(QIcon(":/images/icon32x32.png")); #endif // Try and load a default translation file and install it QTranslator defaultTranslator(&app); if (defaultTranslator.load("default.qm", app.applicationDirPath())) app.installTranslator(&defaultTranslator); app.processEvents(); if (argc > 1) { for (int intCounter = 1; intCounter < argc; intCounter++) { QString argument(argv[intCounter]); if (argument.contains("-databaseURL=", Qt::CaseInsensitive)) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive)) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.contains("-noAuth", Qt::CaseInsensitive)) { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive)) { haveEnhancedAuth = true; _enhancedAuth = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _enhancedAuth = false; } else if (argument.contains("-requireSSL", Qt::CaseInsensitive)) { haveRequireSSL = true; _requireSSL = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _requireSSL = false; } } } _splash = new QSplashScreen(); _splash->setPixmap(QPixmap(":/images/splashEmpty.png")); _evaluation = FALSE; if (!loggedIn) { ParameterList params; params.append("copyright", _Copyright); params.append("version", _Version); params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__)); if (haveUsername) params.append("username", username); if (havePasswd) params.append("password", passwd); if (haveDatabaseURL) params.append("databaseURL", databaseURL); if (haveEnhancedAuth) params.append("enhancedAuth", _enhancedAuth); if (haveRequireSSL) params.append("requireSSL", _requireSSL); if (_evaluation) params.append("evaluation"); if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) params.append("login"); login2 newdlg(0, "", TRUE); newdlg.set(params, _splash); if(newdlg.result() != QDialog::Accepted) { if (newdlg.exec() == QDialog::Rejected) return -1; else { databaseURL = newdlg._databaseURL; username = newdlg.username(); __password = newdlg.password(); } } } XSqlQuery metric; metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'Application')" ); if(!metric.first() || (metric.value("metric_value").toString() == "Standard")) { // check if the xtmfg package is installed metric.exec("SELECT pkghead_name FROM pkghead WHERE pkghead_name='xtmfg'"); if(metric.first()) { _splash->setPixmap(QPixmap(":/images/splashMfgEdition.png")); _Name = _Name.arg("Manufacturing"); } else { _splash->setPixmap(QPixmap(":/images/splashStdEdition.png")); _Name = _Name.arg("Standard"); } } else { _splash->setPixmap(QPixmap(":/images/splashPostBooks.png")); _Name = _Name.arg("PostBooks"); } metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'ServerVersion')" ); if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) { bool disallowMismatch = false; metric.exec("SELECT metric_value FROM metric WHERE(metric_name='DisallowMismatchClientVersion')"); if(metric.first() && (metric.value("metric_value").toString() == "t")) disallowMismatch = true; _splash->hide(); int result; if(disallowMismatch) result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. The system has been configured to disallow " "access in this case.<p>Please contact your systems " "administrator.").arg(_dbVersion), QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default ); else result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. If you continue some or all functionality may " "not work properly or at all. You may also cause other " "problems on the database.<p>Do you want to continue " "anyway?").arg(_dbVersion), QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default ); if(result != QMessageBox::Yes) return 0; _splash->show(); } _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metrics = new Metrics(); _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _preferences = new Preferences(username); _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _privileges = new Privileges(); // Load the translator and set the locale from the User's preferences _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); XSqlQuery langq("SELECT * " "FROM usr, locale LEFT OUTER JOIN" " lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN" " country ON (locale_country_id=country_id) " "WHERE ( (usr_username=CURRENT_USER)" " AND (usr_locale_id=locale_id) );" ); if (langq.first()) { QStringList paths; paths << "dict"; paths << ""; paths << "../dict"; paths << app.applicationDirPath() + "/dict"; paths << app.applicationDirPath(); paths << app.applicationDirPath() + "/../dict"; #if defined Q_WS_MACX paths << app.applicationDirPath() + "/../../../dict"; paths << app.applicationDirPath() + "/../../.."; #endif QStringList files; if (!langq.value("locale_lang_file").toString().isEmpty()) files << langq.value("locale_lang_file").toString(); QString langext; if (!langq.value("lang_abbr2").toString().isEmpty() && !langq.value("country_abbr").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString() + "_" + langq.value("country_abbr").toString().toLower(); } else if (!langq.value("lang_abbr2").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString(); } if(!langext.isEmpty()) { files << "xTuple." + langext; files << "openrpt." + langext; XSqlQuery pkglist("SELECT pkghead_name FROM pkghead WHERE packageIsEnabled(pkghead_name);"); while(pkglist.next()) { files << pkglist.value("pkghead_name").toString() + "." + langext; } } if (files.size() > 0) { bool langFound = false; QTranslator *translator = new QTranslator(&app); for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit) { for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit) { if (DEBUG) qDebug("looking for %s in %s", (*fit).toAscii().data(), (*pit).toAscii().data()); if (translator->load(*fit, *pit)) { app.installTranslator(translator); langFound = true; qDebug("installed %s/%s", (*pit).toAscii().data(), (*fit).toAscii().data()); translator = new QTranslator(&app); break; } } } if (!langFound && !_preferences->boolean("IngoreMissingTranslationFiles")) QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"), QObject::tr("<p>The Translation Dictionaries %1 " "cannot be loaded. Reverting " "to the default dictionary." ) .arg(files.join(QObject::tr(", ")))); } /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or lang#, depending on what information is available */ QString langAbbr = langq.value("lang_abbr2").toString(); QString cntryAbbr = langq.value("country_abbr").toString().toUpper(); if(cntryAbbr == "UK") cntryAbbr = "GB"; if (! langAbbr.isEmpty() && ! cntryAbbr.isEmpty()) QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr)); else if (! langAbbr.isEmpty()) QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString())); else if (langq.value("lang_qt_number").toInt() && langq.value("country_qt_number").toInt()) QLocale::setDefault( QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()), QLocale::Country(langq.value("country_qt_number").toInt()))); else QLocale::setDefault(QLocale::system()); qDebug("Locale set to language %s and country %s", QLocale().languageToString(QLocale().language()).toAscii().data(), QLocale().countryToString(QLocale().country()).toAscii().data()); } else if (langq.lastError().type() != QSqlError::NoError) { systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__); } qApp->processEvents(); QString key; // TODO: Add code to check a few locations - Hopefully done QString keypath; QString keyname; QString keytogether; #ifdef Q_WS_WIN keypath = _metrics->value("CCWinEncKey"); #elif defined Q_WS_MACX keypath = _metrics->value("CCMacEncKey"); #elif defined Q_WS_X11 keypath = _metrics->value("CCLinEncKey"); #endif if (keypath.isEmpty()) keypath = app.applicationDirPath(); if (! keypath.endsWith(QDir::separator())) keypath += QDir::separator(); keyname = _metrics->value("CCEncKeyName"); if (keyname.isEmpty()) { keyname = "xTuple.key"; keytogether = keypath + keyname; QFile kn(keytogether); if(!kn.exists()) keyname = "OpenMFG.key"; } keytogether = keypath + keyname; // qDebug("keytogether: %s", keytogether.toAscii().data()); QFile keyFile(keytogether); if(keyFile.exists()) { if(keyFile.open(QIODevice::ReadOnly)) { key = keyFile.readLine(1024); // strip off any newline characters key = key.trimmed(); } } omfgThis = 0; omfgThis = new GUIClient(databaseURL, username); omfgThis->_key = key; // qDebug("Encryption Key: %s", key.toAscii().data() ); if (key.length() > 0) { _splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metricsenc = new Metricsenc(key); } initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace()); // START code for updating the locale settings if they haven't been already XSqlQuery lc; lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';"); lc.first(); if(lc.value(0).toInt() == 0) { lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');"); lc.exec("SELECT locale_id from locale;"); while(lc.next()) { ParameterList params; params.append("mode","edit"); params.append("locale_id", lc.value(0)); sysLocale lcdlg; lcdlg.set(params); lcdlg.sSave(); } } // END code for updating locale settings QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows())); if (omfgThis->_singleWindow.isEmpty()) { omfgThis->setAttribute(Qt::WA_DeleteOnClose); omfgThis->show(); } // keep this synchronized with GUIClient and user.ui.h else if (omfgThis->_singleWindow == "woTimeClock") { ScriptToolbox sb(0); QWidget* newdlg = sb.openWindow("woTimeClock"); if(newdlg) { XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg); if(mw) { ParameterList params; params.append("captive"); mw->set(params); } newdlg->setAttribute(Qt::WA_DeleteOnClose); QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit())); newdlg->show(); } else {
int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget container; container.resize(640, 680); container.setFocusPolicy ( Qt::NoFocus ); Engine engine(NULL); QMenuBar open_menu_bar(&container); QMenu open_menu("&File", &container); QAction open("&Open", &container); open.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O)); open_menu.addAction(&open); QAction reset("&Reset", &container); reset.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R)); open_menu.addAction(&reset); QAction save("&Save", &container); save.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S)); open_menu.addAction(&save); QAction close("&Close", &container); close.setShortcut(QKeySequence(Qt::ALT + Qt::Key_F4)); open_menu.addAction(&close); QMenu draw_menu("&Drawmodes", &container); QAction points("&Points", &container); points.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_P)); draw_menu.addAction(&points); QAction wire("&Wireframe", &container); wire.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_W)); draw_menu.addAction(&wire); QAction flat("&Flat shaded", &container); flat.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F)); draw_menu.addAction(&flat); QAction smooth("&Smooth shaded", &container); smooth.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_M)); draw_menu.addAction(&smooth); /**** MENU CONVEX HULL ****/ QMenu convex_hull("Convex Hull", &container); QAction calc("&Calculate CH", &container); calc.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C)); convex_hull.addAction(&calc); /**** MENU HELP ****/ QMenu help_menu("&?", &container); QAction help("&Help", &container); help.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_H)); help_menu.addAction(&help); QAction about("&About", &container); about.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_A)); help_menu.addAction(&about); open_menu_bar.addMenu(&open_menu); open_menu_bar.addMenu(&draw_menu); open_menu_bar.addMenu(&convex_hull); open_menu_bar.addMenu(&help_menu); Window_gl window(&container); window.setGeometry(0,22,640, 680); container.show(); QDialog instructions( NULL ); instructions.setFixedSize(300,180); instructions.setWindowTitle("Help"); QLabel instr_text("\nUp - Sposta l'osservatore verso l'alto\nDown - Sposta l'osservatore verso il basso\nLeft - Ruota verso sinistra\nRight - Ruota verso destra\nShift+Up - Zoom In\nShift+Down - Zoom out\n\nSi ricorda che il programma e' in grado di gestire\nsolo files di tipo .OFF.\nAltri formati non sono attualmente supportati.", &instructions); instr_text.setTextFormat(Qt::AutoText); instr_text.setWordWrap(true); instructions.hide(); QDialog credits( NULL ); credits.setFixedSize(300,100); credits.setWindowTitle("Credits"); QLabel cred_text("\tCGVew v.1.7\n\nA cura di Fabio Guggeri ([email protected])\ne Stefano Marras ([email protected]).\n", &credits); cred_text.setTextFormat(Qt::AutoText); cred_text.setWordWrap(true); credits.hide(); QObject::connect( &open, SIGNAL(triggered()), &engine, SLOT(open_file()) ); QObject::connect( &reset, SIGNAL(triggered()), &window, SLOT(reset()) ); QObject::connect( &reset, SIGNAL(triggered()), &engine, SLOT(reset()) ); QObject::connect( &save, SIGNAL(triggered()), &engine, SLOT(save_file()) ); QObject::connect( &points, SIGNAL(triggered()), &window, SLOT(set_p_drawmode()) ); QObject::connect( &wire, SIGNAL(triggered()), &window, SLOT(set_w_drawmode()) ); QObject::connect( &flat, SIGNAL(triggered()), &window, SLOT(set_f_drawmode()) ); QObject::connect( &smooth, SIGNAL(triggered()), &window, SLOT(set_s_drawmode()) ); QObject::connect( &help, SIGNAL(triggered()), &instructions, SLOT(show()) ); QObject::connect( &about, SIGNAL(triggered()), &credits, SLOT(show()) ); QObject::connect( &close, SIGNAL(triggered()), &app, SLOT(quit()) ); QObject::connect( &engine, SIGNAL(send_dcel(QVector<DCEL>&)), &window, SLOT(add_dcel(QVector<DCEL>&)) ); QObject::connect( &calc, SIGNAL(triggered()), &engine, SLOT(calculate_ch()) ); window.setFocus(); return app.exec(); }
bool CreateNewView::createInputDialog() { QWidget * w = new GUICreateNewView(this); w->show(); return true; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); // using Config::config; // if( !config.read()){ // qDebug()<<"config file not exist"; // } // QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8")); int start_year = 2010; int end_year = 2130; QVector<QString> curves; curves.push_back(QObject::tr("北京农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("辽宁农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("浙江农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("上海农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("湖南农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("湖北农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("云南农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("山西农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); QVector<FileInfo> files; FileInfo f1; // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/北京合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("北京合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/辽宁合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("辽宁合计人口概要_回归分释_多龄_农X行_非X行_Z"); f1.m_index = 92; files.push_back(f1); f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/浙江合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/浙江合计人口概要_回归分释_多龄_农X行_非X行_Z"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/上海合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("上海合计人口概要_回归分释_多龄_农X行_非X行_Z"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/湖南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("湖南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/湖北合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("湖北合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/云南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("云南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/山西合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("山西合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); QWidget* l = LineType3::makeLineType3(curves, files, start_year, end_year); l->show(); // //汉字支持 // QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8")); // std::shared_ptr<schememetadata> meta; // if(files.front().m_FileName.contains(QObject::tr("夫妇子女"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_FUFUZINV"))); // } // else if(files.front().m_FileName.contains(QObject::tr("人口概要"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_RENKOUGAIYAO"))); // } // else if(files.front().m_FileName.contains(QObject::tr("生育孩次"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_SHENGYUHAICI"))); // } // else //if(files.front().m_FileName.contains(QObject::tr("政策生育"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_ZHENGCESHENGYU"))); // } // std::shared_ptr<SchemeBuffer> buffer(new SchemeBuffer); // try{ // for(int i=0; i<files.size(); ++i){ // QString filename = files[i].m_FileName.section('/', -1).section('.', 0 ,0); // qDebug()<<"main()"<<filename; // SchemePtr ptr(new Scheme(meta, buffer, filename)); // for(int j=start_year; j<=end_year; ++j){ // double num = ptr->getInstance(j)[files[i].m_index]; // qDebug()<<num; // } // } // } // catch(const RecordNotExist& e){ // qDebug() << "Record not exist at" << e.name(); // } return a.exec(); }
void MainWindow::selectPlugin( Kontact::Plugin *plugin ) { if ( !plugin ) return; if ( plugin->isRunningStandalone() ) { statusBar()->message( i18n( "Application is running standalone. Foregrounding..." ), 1000 ); mSidePane->indicateForegrunding( plugin ); plugin->bringToForeground(); return; } KApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) ); KParts::Part *part = plugin->part(); if ( !part ) { KApplication::restoreOverrideCursor(); KMessageBox::error( this, i18n( "Cannot load part for %1." ) .arg( plugin->title() ) + "\n" + lastErrorMessage() ); plugin->setDisabled( true ); mSidePane->updatePlugins(); return; } // store old focus widget QWidget *focusWidget = kapp->focusWidget(); if ( mCurrentPlugin && focusWidget ) { // save the focus widget only when it belongs to the activated part QWidget *parent = focusWidget->parentWidget(); while ( parent ) { if ( parent == mCurrentPlugin->part()->widget() ) mFocusWidgets.insert( mCurrentPlugin->identifier(), QGuardedPtr<QWidget>( focusWidget ) ); parent = parent->parentWidget(); } } if ( mSidePane ) mSidePane->selectPlugin( plugin ); plugin->select(); mPartManager->setActivePart( part ); QWidget *view = part->widget(); Q_ASSERT( view ); if ( view ) { mPartsStack->raiseWidget( view ); view->show(); if ( mFocusWidgets.contains( plugin->identifier() ) ) { focusWidget = mFocusWidgets[ plugin->identifier() ]; if ( focusWidget ) focusWidget->setFocus(); } else view->setFocus(); mCurrentPlugin = plugin; KAction *newAction = plugin->newActions()->first(); KAction *syncAction = plugin->syncActions()->first(); createGUI( plugin->part() ); KToolBar* navigatorToolBar = findToolBar( "navigatorToolBar" ); // Let the navigator toolbar be always the last one, if it's in the top dockwindow if ( navigatorToolBar && !navigatorToolBar->isHidden() && navigatorToolBar->barPos() == KToolBar::Top ) { topDock()->moveDockWindow( navigatorToolBar, -1 ); } setCaption( i18n( "Plugin dependent window title" ,"%1 - Kontact" ).arg( plugin->title() ) ); if ( newAction ) { mNewActions->setIcon( newAction->icon() ); mNewActions->setText( newAction->text() ); } else { // we'll use the action of the first plugin which offers one PluginList::Iterator it; for ( it = mPlugins.begin(); it != mPlugins.end(); ++it ) { newAction = (*it)->newActions()->first(); if ( newAction ) { mNewActions->setIcon( newAction->icon() ); mNewActions->setText( newAction->text() ); break; } } } if ( mSyncActionsEnabled ) { if ( syncAction ) { mSyncActions->setIcon( syncAction->icon() ); mSyncActions->setText( syncAction->text() ); } else { // we'll use the action of the first plugin which offers one PluginList::Iterator it; for ( it = mPlugins.begin(); it != mPlugins.end(); ++it ) { syncAction = (*it)->syncActions()->first(); if ( syncAction ) { mSyncActions->setIcon( syncAction->icon() ); mSyncActions->setText( syncAction->text() ); break; } } } } } QStringList invisibleActions = plugin->invisibleToolbarActions(); QStringList::ConstIterator it; for ( it = invisibleActions.begin(); it != invisibleActions.end(); ++it ) { KAction *action = part->actionCollection()->action( (*it).latin1() ); if ( action ) { QPtrListIterator<KToolBar> it( toolBarIterator() ); for ( ; it.current() ; ++it ) { action->unplug( it.current() ); } } } KApplication::restoreOverrideCursor(); }
//----------------------------------------------------------------------------- int ctkCheckablePushButtonTest1(int argc, char * argv [] ) { QApplication app(argc, argv); QWidget topLevel; ctkCheckablePushButton button1(QObject::tr("My very long text on button")); ctkCheckablePushButton button2(QObject::tr("Button2")); ctkCheckablePushButton button3(QObject::tr("Button3")); ctkCheckablePushButton button4(QObject::tr("Button4")); ctkCheckablePushButton button5(QObject::tr("Button5")); ctkCheckablePushButton button6(QObject::tr("Button6")); ctkCheckablePushButton button7(QObject::tr("Checkable PushButton")); ctkCheckablePushButton button8(QObject::tr("Connected, Not User Checkable")); ctkCheckablePushButton button9(QObject::tr("Connected, Not User Checkable")); ctkCheckablePushButton button10(QObject::tr("Not Connected, User Checkable")); ctkCheckablePushButton button11(QObject::tr("Not Connected, User Checkable")); ctkCheckablePushButton button12(QObject::tr("Checkbox Not User Checkable\nButton Checkable")); ctkCheckablePushButton button13(QObject::tr("Checkbox and Button User Checkable")); QVBoxLayout *layout= new QVBoxLayout; layout->addWidget(&button1); layout->addWidget(&button2); layout->addWidget(&button3); layout->addWidget(&button4); layout->addWidget(&button5); layout->addWidget(&button6); layout->addWidget(&button7); layout->addWidget(&button8); layout->addWidget(&button9); layout->addWidget(&button10); layout->addWidget(&button11); layout->addWidget(&button12); layout->addWidget(&button13); topLevel.setLayout(layout); topLevel.show(); button1.setButtonTextAlignment(Qt::AlignRight | Qt::AlignVCenter); if (button1.buttonTextAlignment() != (Qt::AlignRight | Qt::AlignVCenter)) { std::cerr << "ctkCheckablePushButton::setButtonTextAlignment failed." << std::endl; return EXIT_FAILURE; } button2.setIndicatorAlignment(Qt::AlignRight); if (button2.indicatorAlignment() != Qt::AlignRight) { std::cerr << "ctkCheckablePushButton::setIndicatorAlignment failed." << std::endl; return EXIT_FAILURE; } button3.setButtonTextAlignment(Qt::AlignCenter); button3.setIndicatorAlignment(Qt::AlignCenter); button3.setCheckable(true); button4.setCheckable(true); button4.toggle(); button5.setButtonTextAlignment(Qt::AlignCenter); button5.setIndicatorAlignment(Qt::AlignRight); button6.setIndicatorAlignment(Qt::AlignTop); button7.setButtonTextAlignment(Qt::AlignCenter); button7.setIndicatorAlignment(Qt::AlignLeft); // Connected to button, not user checkable: button8.setCheckBoxUserCheckable(false); button8.setCheckState(Qt::Checked); button9.setCheckBoxUserCheckable(false); button9.setCheckState(Qt::Unchecked); // Not connected to button, user checkable: button10.setCheckBoxControlsButton(false); button10.setCheckState(Qt::Checked); button11.setCheckBoxControlsButton(false); button11.setCheckState(Qt::PartiallyChecked); button12.setCheckBoxControlsButton(false); button12.setCheckBoxUserCheckable(false); button12.setCheckable(true); button13.setCheckBoxControlsButton(false); button13.setCheckBoxUserCheckable(true); button13.setCheckable(true); if (argc < 2 || QString(argv[1]) != "-I" ) { QTimer::singleShot(200, &app, SLOT(quit())); } return app.exec(); }
void KexiDBAutoField::createEditor() { if (subwidget()) { delete(QWidget *)subwidget(); } QWidget *newSubwidget; //kDebug() << "widgetType:" << d->widgetType; switch (d->widgetType) { case Text: case Double: //! @todo setup validator case Integer: //! @todo setup validator case Date: case Time: case DateTime: { KexiDBLineEdit *le = new KexiDBLineEdit(this); newSubwidget = le; le->setFrame(false); break; } case MultiLineText: newSubwidget = new KexiDBTextEdit(this); break; case Boolean: newSubwidget = new KexiDBCheckBox(dataSource(), this); break; case Image: newSubwidget = new KexiDBImageBox(designMode(), this); break; case ComboBox: { KexiDBComboBox *cbox = new KexiDBComboBox(this); newSubwidget = cbox; cbox->setDesignMode(designMode()); break; } default: newSubwidget = 0; changeText(d->caption); break; } //kDebug() << newSubwidget; setSubwidget(newSubwidget); //this will also allow to declare subproperties, see KFormDesigner::WidgetWithSubpropertiesInterface if (newSubwidget) { newSubwidget->setObjectName( QString::fromLatin1("KexiDBAutoField_") + newSubwidget->metaObject()->className()); dynamic_cast<KexiDataItemInterface*>(newSubwidget)->setParentDataItemInterface(this); dynamic_cast<KexiFormDataItemInterface*>(newSubwidget) ->setColumnInfo(columnInfo()); //needed at least by KexiDBImageBox dynamic_cast<KexiFormDataItemInterface*>(newSubwidget) ->setVisibleColumnInfo(visibleColumnInfo()); //needed at least by KexiDBComboBox newSubwidget->setProperty("dataSource", dataSource()); //needed at least by KexiDBImageBox KFormDesigner::DesignTimeDynamicChildWidgetHandler::childWidgetAdded(this); newSubwidget->show(); d->label->setBuddy(newSubwidget); if (d->focusPolicyChanged) {//if focusPolicy is changed at top level, editor inherits it newSubwidget->setFocusPolicy(focusPolicy()); } else {//if focusPolicy is not changed at top level, inherit it from editor QWidget::setFocusPolicy(newSubwidget->focusPolicy()); } setFocusProxy(newSubwidget); //ok? if (parentWidget()) newSubwidget->setPalette(qApp->palette()); copyPropertiesToEditor(); } setLabelPosition(labelPosition()); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); { //! [0] QWidget *window = new QWidget; //! [0] //! [1] QPushButton *button1 = new QPushButton("One"); //! [1] //! [2] QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); //! [2] //! [3] QHBoxLayout *layout = new QHBoxLayout; //! [3] //! [4] layout->addWidget(button1); layout->addWidget(button2); layout->addWidget(button3); layout->addWidget(button4); layout->addWidget(button5); window->setLayout(layout); //! [4] window->setWindowTitle("QHBoxLayout"); //! [5] window->show(); //! [5] } { //! [6] QWidget *window = new QWidget; //! [6] //! [7] QPushButton *button1 = new QPushButton("One"); //! [7] //! [8] QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); //! [8] //! [9] QVBoxLayout *layout = new QVBoxLayout; //! [9] //! [10] layout->addWidget(button1); layout->addWidget(button2); layout->addWidget(button3); layout->addWidget(button4); layout->addWidget(button5); window->setLayout(layout); //! [10] window->setWindowTitle("QVBoxLayout"); //! [11] window->show(); //! [11] } { //! [12] QWidget *window = new QWidget; //! [12] //! [13] QPushButton *button1 = new QPushButton("One"); //! [13] //! [14] QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); //! [14] //! [15] QGridLayout *layout = new QGridLayout; //! [15] //! [16] layout->addWidget(button1, 0, 0); layout->addWidget(button2, 0, 1); layout->addWidget(button3, 1, 0, 1, 2); layout->addWidget(button4, 2, 0); layout->addWidget(button5, 2, 1); window->setLayout(layout); //! [16] window->setWindowTitle("QGridLayout"); //! [17] window->show(); //! [17] } { //! [18] QWidget *window = new QWidget; //! [18] //! [19] QPushButton *button1 = new QPushButton("One"); QLineEdit *lineEdit1 = new QLineEdit(); //! [19] //! [20] QPushButton *button2 = new QPushButton("Two"); QLineEdit *lineEdit2 = new QLineEdit(); QPushButton *button3 = new QPushButton("Three"); QLineEdit *lineEdit3 = new QLineEdit(); //! [20] //! [21] QFormLayout *layout = new QFormLayout; //! [21] //! [22] layout->addRow(button1, lineEdit1); layout->addRow(button2, lineEdit2); layout->addRow(button3, lineEdit3); window->setLayout(layout); //! [22] window->setWindowTitle("QFormLayout"); //! [23] window->show(); //! [23] } { //! [24] QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(formWidget); setLayout(layout); //! [24] } return app.exec(); }
void tst_qquickwidget::resizemodeitem() { QWidget window; window.setGeometry(0, 0, 400, 400); QScopedPointer<QQuickWidget> view(new QQuickWidget); view->setParent(&window); view->setResizeMode(QQuickWidget::SizeRootObjectToView); QCOMPARE(QSize(0,0), view->initialSize()); view->setSource(testFileUrl("resizemodeitem.qml")); QQuickItem* item = qobject_cast<QQuickItem*>(view->rootObject()); QVERIFY(item); window.show(); view->showNormal(); // initial size from root object QCOMPARE(item->width(), 200.0); QCOMPARE(item->height(), 200.0); QCOMPARE(view->size(), QSize(200, 200)); QCOMPARE(view->size(), view->sizeHint()); QCOMPARE(view->size(), view->initialSize()); // size update from view view->resize(QSize(80,100)); QTRY_COMPARE(item->width(), 80.0); QCOMPARE(item->height(), 100.0); QCOMPARE(view->size(), QSize(80, 100)); QCOMPARE(view->size(), view->sizeHint()); view->setResizeMode(QQuickWidget::SizeViewToRootObject); // size update from view disabled view->resize(QSize(60,80)); QCOMPARE(item->width(), 80.0); QCOMPARE(item->height(), 100.0); QTRY_COMPARE(view->size(), QSize(60, 80)); // size update from root object item->setWidth(250); item->setHeight(350); QCOMPARE(item->width(), 250.0); QCOMPARE(item->height(), 350.0); QTRY_COMPARE(view->size(), QSize(250, 350)); QCOMPARE(view->size(), QSize(250, 350)); QCOMPARE(view->size(), view->sizeHint()); // reset window window.hide(); view.reset(new QQuickWidget(&window)); view->setResizeMode(QQuickWidget::SizeViewToRootObject); view->setSource(testFileUrl("resizemodeitem.qml")); item = qobject_cast<QQuickItem*>(view->rootObject()); QVERIFY(item); window.show(); view->showNormal(); // initial size for root object QCOMPARE(item->width(), 200.0); QCOMPARE(item->height(), 200.0); QCOMPARE(view->size(), view->sizeHint()); QCOMPARE(view->size(), view->initialSize()); // size update from root object item->setWidth(80); item->setHeight(100); QCOMPARE(item->width(), 80.0); QCOMPARE(item->height(), 100.0); QTRY_COMPARE(view->size(), QSize(80, 100)); QCOMPARE(view->size(), view->sizeHint()); // size update from root object disabled view->setResizeMode(QQuickWidget::SizeRootObjectToView); item->setWidth(60); item->setHeight(80); QCOMPARE(view->width(), 80); QCOMPARE(view->height(), 100); QCOMPARE(QSize(item->width(), item->height()), view->sizeHint()); // size update from view view->resize(QSize(200,300)); QTRY_COMPARE(item->width(), 200.0); QCOMPARE(item->height(), 300.0); QCOMPARE(view->size(), QSize(200, 300)); QCOMPARE(view->size(), view->sizeHint()); window.hide(); // if we set a specific size for the view then it should keep that size // for SizeRootObjectToView mode. view.reset(new QQuickWidget(&window)); view->resize(300, 300); view->setResizeMode(QQuickWidget::SizeRootObjectToView); QCOMPARE(QSize(0,0), view->initialSize()); view->setSource(testFileUrl("resizemodeitem.qml")); view->resize(300, 300); item = qobject_cast<QQuickItem*>(view->rootObject()); QVERIFY(item); window.show(); view->showNormal(); // initial size from root object QCOMPARE(item->width(), 300.0); QCOMPARE(item->height(), 300.0); QTRY_COMPARE(view->size(), QSize(300, 300)); QCOMPARE(view->size(), view->sizeHint()); QCOMPARE(view->initialSize(), QSize(200, 200)); // initial object size }
//----------------------------------------------------------------------------- int ctkVTKSliceViewTest1(int argc, char * argv [] ) { QApplication app(argc, argv); // Test arguments QString filename = "HeadMRVolume.mhd"; // Command line parser ctkCommandLineParser parser; parser.addArgument("", "-I", QVariant::Bool); parser.addArgument("", "-D", QVariant::String); bool ok = false; QHash<QString, QVariant> parsedArgs = parser.parseArguments(app.arguments(), &ok); if (!ok) { std::cerr << qPrintable(parser.errorString()) << std::endl; return EXIT_FAILURE; } bool interactive = parsedArgs["-I"].toBool(); QString data_directory = parsedArgs["-D"].toString(); QString imageFilename = data_directory + "/" + filename; // Instanciate the reader factory vtkSmartPointer<vtkImageReader2Factory> imageFactory = vtkSmartPointer<vtkImageReader2Factory>::New(); // Instanciate an image reader vtkSmartPointer<vtkImageReader2> imageReader; imageReader.TakeReference(imageFactory->CreateImageReader2(imageFilename.toLatin1())); if (!imageReader) { std::cerr << "Failed to instanciate image reader using: " << qPrintable(imageFilename) << std::endl; return EXIT_FAILURE; } // Read image imageReader->SetFileName(imageFilename.toLatin1()); imageReader->Update(); vtkSmartPointer<vtkImageData> image = imageReader->GetOutput(); // Top level widget QWidget widget; // .. and its associated layout QVBoxLayout * topLevelLayout = new QVBoxLayout(&widget); topLevelLayout->setContentsMargins(0, 0, 0, 0); // Horizontal layout to contain the spinboxes QHBoxLayout * spinBoxLayout = new QHBoxLayout; topLevelLayout->addLayout(spinBoxLayout); int defaultRowCount = 4; int defaultColumnCount = 3; // SpinBox to change number of row in lightBox QSpinBox * rowSpinBox = new QSpinBox; rowSpinBox->setRange(1, 10); rowSpinBox->setSingleStep(1); rowSpinBox->setValue(defaultRowCount); spinBoxLayout->addWidget(rowSpinBox); // SpinBox to change number of column in lightBox QSpinBox * columnSpinBox = new QSpinBox; columnSpinBox->setRange(1, 10); columnSpinBox->setSingleStep(1); columnSpinBox->setValue(defaultColumnCount); spinBoxLayout->addWidget(columnSpinBox); ctkVTKSliceView * sliceView = new ctkVTKSliceView; sliceView->setRenderEnabled(true); sliceView->setMinimumSize(600, 600); sliceView->setImageData(image); sliceView->setHighlightedBoxColor(QColor(Qt::yellow)); sliceView->lightBoxRendererManager()->SetRenderWindowLayout(defaultRowCount, defaultColumnCount); sliceView->lightBoxRendererManager()->SetHighlighted(0, 0, true); sliceView->setCornerAnnotationText("CTK"); sliceView->scheduleRender(); topLevelLayout->addWidget(sliceView); // Set connection QObject::connect(rowSpinBox, SIGNAL(valueChanged(int)), sliceView, SLOT(setLightBoxRendererManagerRowCount(int))); QObject::connect(columnSpinBox, SIGNAL(valueChanged(int)), sliceView, SLOT(setLightBoxRendererManagerColumnCount(int))); ctkVTKObjectEventsObserver vtkObserver; vtkObserver.addConnection(sliceView->lightBoxRendererManager(), vtkCommand::ModifiedEvent, sliceView, SLOT(scheduleRender())); widget.show(); // TODO Add image regression test if (!interactive) { QTimer::singleShot(1000, &app, SLOT(quit())); } return app.exec(); }
bool FrameAttachmentPoint::attach(AttachableFrame* frame) { QLayout* layout; QWidget* attWidget; QFrame* attFrame; QDockWidget* attDockWidget; QTabWidget* attTabWidget; QMainWindow* attMainWindow; int index = 0; if ((int)mAttachedFrames.size() >= mMaxAttachmentCount) { LOG_ERROR() << "FrameAttachmentPoint::attach(): cannot attach more than " << mMaxAttachmentCount << " Frame" << (mMaxAttachmentCount > 1 ? "s" : "") << " to Attachment Point " << mName << "."; return false; } //Attach the frame in a way depending on its type switch (mType) { case ATTACHMENT_NONE: LOG_ERROR() << "FrameAttachmentPoint::attach(): cannot attach to illegal Attachment Point."; return false; break; case ATTACHMENT_WIDGET: //Attach to Widget with adding a new layout layout = WindowManager::createNeutralLayout(); layout->addWidget(&*frame); frame->show(); attWidget = (dynamic_cast<QWidget*>(mAttachmentPoint)); attWidget->setLayout(layout); attWidget->show(); break; case ATTACHMENT_FRAME: //Attach to Frame with adding a new layout layout = WindowManager::createNeutralLayout(); layout->addWidget(&*frame); frame->show(); attFrame = (dynamic_cast<QFrame*>(mAttachmentPoint)); attFrame->setLayout(layout); attFrame->show(); break; case ATTACHMENT_TABWIDGET: //Attach to TabWidget with adding a new page and (automatically) a layout attTabWidget = (dynamic_cast<QTabWidget*>(mAttachmentPoint)); index = attTabWidget->addTab(&*frame, frame->getCaption()); WindowManager::changeToNeutralLayout(attTabWidget->widget(index)->layout()); break; case ATTACHMENT_DOCKWIDGET: //Attach to DockWidget with adding a new layout layout = WindowManager::createNeutralLayout(); layout->addWidget(&*frame); frame->show(); attDockWidget = (dynamic_cast<QDockWidget*>(mAttachmentPoint)); attDockWidget->setLayout(layout); attDockWidget->show(); break; case ATTACHMENT_MAINWINDOW: //Attach to MainWindow with adding a new layout layout = WindowManager::createNeutralLayout(); layout->addWidget(&*frame); frame->show(); attMainWindow = (dynamic_cast<QMainWindow*>(mAttachmentPoint)); attMainWindow->setLayout(layout); attMainWindow->show(); break; default: LOG_ERROR() << "FrameAttachmentPoint::attach(): unknown Attachment Point."; return false; break; } //Store the attachment pointer mAttachedFrames.insert(frame->getPluginId(), frame); return true; }
void QTextBrowser::popupDetail( const QString& contents, const QPoint& pos ) { const int shadowWidth = 6; // also used as '5' and '6' and even '8' below const int vMargin = 8; const int hMargin = 12; QWidget* popup = new QTextDetailPopup; popup->setBackgroundMode( QWidget::NoBackground ); QSimpleRichText* doc = new QSimpleRichText( contents, popup->font() ); doc->adjustSize(); QRect r( 0, 0, doc->width(), doc->height() ); int w = r.width() + 2*hMargin; int h = r.height() + 2*vMargin; popup->resize( w + shadowWidth, h + shadowWidth ); // okay, now to find a suitable location //###### we need a global fancy popup positioning somewhere popup->move(pos - popup->rect().center()); if (popup->geometry().right() > QApplication::desktop()->width()) popup->move( QApplication::desktop()->width() - popup->width(), popup->y() ); if (popup->geometry().bottom() > QApplication::desktop()->height()) popup->move( popup->x(), QApplication::desktop()->height() - popup->height() ); if ( popup->x() < 0 ) popup->move( 0, popup->y() ); if ( popup->y() < 0 ) popup->move( popup->x(), 0 ); popup->show(); // now for super-clever shadow stuff. super-clever mostly in // how many window system problems it skirts around. QPainter p( popup ); p.setPen( QApplication::palette().active().foreground() ); p.drawRect( 0, 0, w, h ); p.setPen( QApplication::palette().active().mid() ); p.setBrush( QColor( 255, 255, 240 ) ); p.drawRect( 1, 1, w-2, h-2 ); p.setPen( black ); doc->draw( &p, hMargin, vMargin, r, popup->colorGroup(), 0 ); delete doc; p.drawPoint( w + 5, 6 ); p.drawLine( w + 3, 6, w + 5, 8 ); p.drawLine( w + 1, 6, w + 5, 10 ); int i; for( i=7; i < h; i += 2 ) p.drawLine( w, i, w + 5, i + 5 ); for( i = w - i + h; i > 6; i -= 2 ) p.drawLine( i, h, i + 5, h + 5 ); for( ; i > 0 ; i -= 2 ) p.drawLine( 6, h + 6 - i, i + 5, h + 5 ); }
void MainWindowVideos::selected(IVideo * pVideo) { // TODO merge with logic from channel QWidget * lPopup = new QWidget(this, Qt::Popup); QPushButton * lButton; lPopup->setAttribute(Qt::WA_DeleteOnClose); lPopup->setLayout(new QBoxLayout(QBoxLayout::TopToBottom, lPopup)); lButton = new QPushButton(lPopup); lButton->setText("Watch!"); QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup] { lPopup->setEnabled(false); QUrl lUrl = pVideo->videoUrl(IVideo::URL_VIDEO_DIRECT); lPopup->close(); if (!lUrl.isValid()) return; QString lProgram; QStringList lArguments; lProgram = "/usr/bin/mpv"; if (QFile::exists(lProgram)) { lArguments << "--untimed"; lArguments << "--quiet"; } else { lProgram = "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe"; if (!QFile::exists(lProgram)) lProgram = "C:\\Program Files\\VLC\\vlc.exe"; if (!QFile::exists(lProgram)) lProgram = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe"; if (!QFile::exists(lProgram)) lProgram = "C:\\Program Files (x86)\\VLC\\vlc.exe"; } lArguments << lUrl.toString(QUrl::FullyEncoded); QProcess * lProcess = new QProcess(); QObject::connect(lProcess, (void (QProcess::*) (int))&QProcess::finished, [lProcess] (int pExitCode) { lProcess->deleteLater(); }); lProcess->setProcessChannelMode(QProcess::ForwardedChannels); lProcess->setProgram(lProgram); lProcess->setArguments(lArguments); lProcess->start(); }); lPopup->layout()->addWidget(lButton); lButton = new QPushButton(lPopup); lButton->setText("Open in browser"); QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup] { lPopup->setEnabled(false); QUrl lUrl = pVideo->videoUrl(IVideo::URL_VIDEO_WEBSITE); lPopup->close(); if (!lUrl.isValid()) return; QDesktopServices::openUrl(lUrl); }); lPopup->layout()->addWidget(lButton); lButton = new QPushButton(lPopup); lButton->setText("Download ..."); QObject::connect(lButton, &QPushButton::clicked, [pVideo,lPopup] { lPopup->setEnabled(false); IDownloader * lDownloader = pVideo->downloader(); lPopup->close(); if (lDownloader == nullptr) return; DownloadWindow * lWindow = new DownloadWindow(lDownloader); lWindow->setAttribute(Qt::WA_DeleteOnClose); lWindow->show(); }); lPopup->layout()->addWidget(lButton); lPopup->move(QCursor::pos() - QPoint(5, 10)); lPopup->show(); }
QTextDocument * Exporter::buildFinalDoc() { //search for checked items : QDomDocument domDoc = hub->project()->mainTreeDomDoc(); QDomElement root = domDoc.documentElement(); QList<QDomElement> itemList = searchForCheckedItems(root); if(itemList.size() == 0) return new QTextDocument(); // set up the progress bar : QWidget *progressWidget = new QWidget(this, Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); QHBoxLayout *progressLayout = new QHBoxLayout(progressWidget); QProgressBar *progressBar = new QProgressBar(progressWidget); int progressValue = 0; progressLayout->addWidget(progressBar); progressWidget->setLayout(progressLayout); progressBar->setMaximum(itemList.size()); progressBar->setValue(progressValue); progressWidget->show(); // QString debug; // qDebug() << "itemList" << debug.setNum(itemList->size()); QTextDocument *textDocument = new QTextDocument(this); QTextEdit *edit = new QTextEdit(this); textDocument->setDefaultStyleSheet("p, li { white-space: pre-wrap; } p{line-height: 2em; font-family:'Liberation Serif'; font-size:12pt;margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:72px;}"); for(int i = 0; i < itemList.size(); ++i){ QDomElement element = itemList.at(i); QTextCursor *tCursor = new QTextCursor(textDocument); QTextBlockFormat blockFormatLeft; blockFormatLeft.setBottomMargin(0); blockFormatLeft.setTopMargin(0); blockFormatLeft.setTextIndent(72); blockFormatLeft.setLineHeight(200, QTextBlockFormat::ProportionalHeight); blockFormatLeft.setAlignment(Qt::AlignJustify); QTextCharFormat charFormatLeft; charFormatLeft.setFontPointSize(12); charFormatLeft.setFontFamily("Courrier"); QTextBlockFormat blockFormatCenter; blockFormatCenter.setAlignment(Qt::AlignCenter); if(element.tagName() != "separator"){ qDebug() << "element name : "+ element.attribute("name"); MainTextDocument *textDoc = hub->project()->findChild<MainTextDocument *>("textDoc_" + element.attribute("number")); MainTextDocument *synDoc = hub->project()->findChild<MainTextDocument *>("synDoc_" + element.attribute("number")); MainTextDocument *noteDoc = hub->project()->findChild<MainTextDocument *>("noteDoc_" + element.attribute("number")); QTextDocumentFragment textFrag(prepareTextDoc(textDoc)); QTextDocumentFragment synFrag(prepareSynDoc(synDoc)); QTextDocumentFragment noteFrag(prepareNoteDoc(noteDoc)); edit->setDocument(textDocument); if(element.tagName() == "book"){ textDocument->setMetaInformation(QTextDocument::DocumentTitle,element.attribute("name", "")); edit->append("<h1>" + element.attribute("name", "") + "</h1>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<h4>" + QDateTime::currentDateTime().toString() + "</h4>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); edit->append("<br>"); } if(element.tagName() == "act"){ edit->append("<br>"); edit->append("<br>"); edit->append("<h2>" + element.attribute("name", "") + "</h2>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); } if(element.tagName() == "chapter"){ edit->append("<br>"); edit->append("<br>"); edit->append("<h2>" + element.attribute("name", "") + "</h2>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); } if(element.tagName() == "scene" && ui->setSceneTitlesComboBox->currentIndex() != 0){ QString sceneTitle; switch (ui->setSceneTitlesComboBox->currentIndex()){ case 1: sceneTitle = element.attribute("name", ""); break; case 2: sceneTitle = "###"; break; case 3: sceneTitle = "***"; break; default: sceneTitle = element.attribute("name", ""); break; } edit->append("<br>"); edit->append("<h3>" + sceneTitle + "</h3>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); } if(ui->synopsisCheckBox->isChecked() && !synFrag.isEmpty()){ edit->append("<br>"); edit->append("<h4>" + tr("Synopsis") + "</h4>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->insertBlock(blockFormatLeft, charFormatLeft); tCursor->insertFragment(synFrag); } if(ui->notesCheckBox->isChecked() && !noteFrag.isEmpty()){ edit->append("<br>"); edit->append("<h4>" + tr("Note") + "</h4>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->insertBlock(blockFormatLeft, charFormatLeft); tCursor->insertFragment(noteFrag); } if(ui->storyCheckBox->isChecked()){ if((ui->synopsisCheckBox->isChecked() || ui->notesCheckBox->isChecked()) && !textFrag.isEmpty()){ tCursor->insertBlock(); tCursor->insertHtml("<h4>" + tr("Story") + "</h4>"); tCursor->mergeBlockFormat(blockFormatCenter); tCursor->insertBlock(); } tCursor->insertHtml("<br>"); // tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->insertBlock(blockFormatLeft, charFormatLeft); tCursor->insertFragment(textFrag); // edit->append(textFrag->toHtml()); } } else if(element.tagName() == "separator"){ edit->append("<br>"); edit->append("<h3>#</h3>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatCenter); edit->append("<br>"); tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1); tCursor->mergeBlockFormat(blockFormatLeft); } progressValue += 1; progressBar->setValue(progressValue); } QRegExp reg("-qt-paragraph-type:.*;|margin-top:.*;|margin-bottom:.*;|margin-left:.*;|margin-right:.*;|-qt-block-indent:.*;|text-indent:.*;|font-family:.*;|font-size:.*;"); reg.setMinimal(true); textDocument->setHtml(textDocument->toHtml().remove(reg)); //find and change final page css style : //textDocument->setDefaultStyleSheet("p, li { white-space: pre-wrap; } p{line-height: 2em; font-family:'Liberation Serif'; font-size:14pt;margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:72px;}"); // <style type="text/css"> // p, li { white-space: pre-wrap; } // </style> // tCursor // qDebug() << textDocument->toHtml(); progressWidget->close(); return textDocument; }
int Dialog::showDialog(const QString& view, QObject* viewModel, int type) { QDialog* dialog = NULL; QMainWindow* mainWindow = NULL; QWidget* windowWidget = NULL; QWidget* layoutWidget = NULL; switch (type) { case Dialog::MainWindow: mainWindow = new QMainWindow(); windowWidget = mainWindow; layoutWidget = new QWidget(windowWidget); mainWindow->setCentralWidget(layoutWidget); break; case Dialog::ModalDialog: dialog = new QDialog(QApplication::activeWindow()); windowWidget = dialog; layoutWidget = dialog; break; default: dialog = new QDialog(); windowWidget = dialog; layoutWidget = dialog; break; } QGridLayout* layout = new QGridLayout(layoutWidget); // Create view QDeclarativeView* v = new QDeclarativeView(layoutWidget); if (viewModel) { int count = viewModel->metaObject()->propertyCount(); for (int i = 0; i < count; ++i) { QMetaProperty p = viewModel->metaObject()->property(i); if (p.isReadable() && p.typeName() == QString("QDeclarativeImageProvider*")) { QString name = p.name(); QDeclarativeImageProvider* value = p.read(viewModel).value<QDeclarativeImageProvider*>(); v->engine()->addImageProvider(name.toLatin1(), new ProxyImageProvider(value)); } } v->rootContext()->setContextProperty("dataContext", viewModel); } QString path; foreach (path, importPaths) v->engine()->addImportPath(path); foreach (path, pluginPaths) v->engine()->addPluginPath(path); v->setSource(QUrl(view)); v->setResizeMode(QDeclarativeView::SizeRootObjectToView); // Initialize dialog QGraphicsObject* root = v->rootObject(); QVariant property = root->property("dialogTitle"); if (property.isValid()) windowWidget->setWindowTitle(property.toString()); property = root->property("dialogMinWidth"); if (property.isValid()) layoutWidget->setMinimumWidth(property.toInt()); property = root->property("dialogMinHeight"); if (property.isValid()) layoutWidget->setMinimumHeight(property.toInt()); property = root->property("dialogMaxWidth"); if (property.isValid()) layoutWidget->setMaximumWidth(property.toInt()); property = root->property("dialogMaxHeight"); if (property.isValid()) layoutWidget->setMaximumHeight(property.toInt()); property = root->property("dialogResizable"); if (property.isValid() && !property.toBool()) layout->setSizeConstraint(QLayout::SetFixedSize); Qt::WindowStates states = windowWidget->windowState(); Qt::WindowFlags flags = windowWidget->windowFlags(); property = root->property("dialogMinimizeButton"); if (property.isValid()) flags = property.toBool() ? flags | Qt::WindowMinimizeButtonHint : flags & ~Qt::WindowMinimizeButtonHint; property = root->property("dialogMaximizeButton"); if (property.isValid()) flags = property.toBool() ? flags | Qt::WindowMaximizeButtonHint : flags & ~Qt::WindowMaximizeButtonHint; property = root->property("dialogCloseButton"); if (property.isValid()) flags = property.toBool() ? flags | Qt::WindowCloseButtonHint : flags & ~Qt::WindowCloseButtonHint; property = root->property("dialogFullScreen"); if (property.isValid()) states = property.toBool() ? states | Qt::WindowFullScreen : states & ~Qt::WindowFullScreen; flags = flags & ~Qt::WindowContextHelpButtonHint; windowWidget->setWindowFlags(flags); windowWidget->setWindowState(states); property = root->property("dialogToolBar"); if (type == Dialog::MainWindow && property.isValid() && property.typeName() == QString("QDeclarativeListProperty<QDeclarativeItem>")) { QToolBar* toolbar = new QToolBar(mainWindow); toolbar->setMovable(false); toolbar->setFloatable(false); toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); toolbar->setAllowedAreas(Qt::TopToolBarArea); QDeclarativeListProperty<QDeclarativeItem> btnList = property.value< QDeclarativeListProperty<QDeclarativeItem> >(); int btnCount = btnList.count(&btnList); for (int i = 0; i < btnCount; ++i) { QDeclarativeItem* item = btnList.at(&btnList, i); if (!item->property("text").isValid()) continue; QString itemText = item->property("text").toString(); QString itemTooltip = item->property("tooltip").isValid() ? item->property("tooltip").toString() : ""; QString itemIconSource = item->property("iconSource").isValid() ? item->property("iconSource").toString() : ""; int itemIconSize = item->property("iconSize").isValid() ? item->property("iconSize").toInt() : -1; if (itemText == "|") { toolbar->addSeparator(); } else if (itemText == "-") { QWidget* spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); toolbar->addWidget(spacer); } else { QAction* action = new QAction(mainWindow); action->setText(itemText); action->setToolTip(itemTooltip); action->setIcon(QIcon(itemIconSource)); QObject::connect(action, SIGNAL(triggered()), item, SLOT(trigger())); if (item->property("enabled").isValid()) new PropertyBinding(action, "enabled", item, "enabled", PropertyBinding::OneWay, NULL, this); if (item->property("visible").isValid()) new PropertyBinding(action, "visible", item, "visible", PropertyBinding::OneWay, NULL, this); toolbar->addAction(action); } if (itemIconSize != -1) toolbar->setIconSize(QSize(itemIconSize, itemIconSize)); } mainWindow->setUnifiedTitleAndToolBarOnMac(true); mainWindow->addToolBar(toolbar); } property = root->property("dialogMenu"); if (type == Dialog::MainWindow && property.isValid() && property.typeName() == QString("QDeclarativeListProperty<QDeclarativeItem>")) { QDeclarativeListProperty<QDeclarativeItem> list = property.value< QDeclarativeListProperty<QDeclarativeItem> >(); int count = list.count(&list); for (int i = 0; i < count; ++i) { QDeclarativeItem* item = list.at(&list, i); if (!item->property("text").isValid()) continue; QString itemText = item->property("text").toString(); QMenu * menuItem = mainWindow->menuBar()->addMenu(itemText); if (!item->property("submenu").isValid() || item->property("submenu").typeName() != QString("QDeclarativeListProperty<QDeclarativeItem>")) continue; QDeclarativeListProperty<QDeclarativeItem> innerList = item->property("submenu").value< QDeclarativeListProperty<QDeclarativeItem> >(); int innerCount = innerList.count(&innerList); for (int j = 0; j < innerCount; ++j) { QDeclarativeItem* innerItem = innerList.at(&innerList, j); if (!innerItem->property("text").isValid()) continue; QString innerItemText = innerItem->property("text").toString(); QString innerItemShortcut = innerItem->property("shortcut").isValid() ? innerItem->property("shortcut").toString() : ""; QString innerItemIconSource = innerItem->property("iconSource").isValid() ? innerItem->property("iconSource").toString() : ""; if (innerItemText == "-") { menuItem->addSeparator(); } else { QAction * action = menuItem->addAction(QIcon(innerItemIconSource), innerItemText); action->setShortcut(QKeySequence(innerItemShortcut)); QObject::connect(action, SIGNAL(triggered()), innerItem, SLOT(trigger())); if (innerItem->property("enabled").isValid()) new PropertyBinding(action, "enabled", innerItem, "enabled", PropertyBinding::OneWay, NULL, this); if (innerItem->property("visible").isValid()) new PropertyBinding(action, "visible", innerItem, "visible", PropertyBinding::OneWay, NULL, this); } } } } new DialogCallbacks(windowWidget, v, root); // Initialize layout layout->setMargin(0); layout->addWidget(v, 0, 0); // Execute switch (type) { case Dialog::ModalDialog: dialog->exec(); break; case Dialog::MainWindow: { if (mainWindowGeometry.isEmpty()) { mainWindow->adjustSize(); mainWindow->move(QApplication::desktop()->screen()->rect().center() - mainWindow->rect().center()); } else mainWindow->restoreGeometry(mainWindowGeometry); } default: windowWidget->setAttribute(Qt::WA_DeleteOnClose); windowWidget->show(); break; } int result = 0; property = root->property("dialogResult"); if (property.isValid()) result = property.toInt(); if (type == Dialog::ModalDialog) delete dialog; return result; }
int main(int argc, char **argv) { QApplication app(argc, argv); QWidget *window = new QWidget; window->setWindowTitle("Real Life simulator: zwierzyna kontra predator"); QHBoxLayout *layout = new QHBoxLayout; QVBoxLayout *settings = new QVBoxLayout(); PlotArea *plot = new PlotArea(); // ******************************************************************************** QLabel *labA = new QLabel("Wsp. smierci drapieznikow z powodu braku ofiar (0,1]"); QSlider *slA = new QSlider(Qt::Horizontal); slA->setMaximum((int)sliderAmax); slA->setMinimum(1); slA->setValue(0.1*sliderAmax); settings->addWidget(labA); settings->addWidget(slA); QObject::connect(slA,SIGNAL(valueChanged(int)),plot,SLOT(setA(int))); QLabel *labB = new QLabel("Wsp. narodzin ofiar, gdy nie ma drapieznikow (0,1]"); QSlider *slB = new QSlider(Qt::Horizontal); slB->setMaximum((int)sliderBmax); slB->setMinimum(1); slB->setValue(0.1*sliderBmax); settings->addWidget(labB); settings->addWidget(slB); QObject::connect(slB,SIGNAL(valueChanged(int)),plot,SLOT(setB(int))); QLabel *labC = new QLabel("Efektywnosc, z jaka drapieznik wykorzystuje energie\npozyskana ze zjedzenia ofiar (0,1]"); QSlider *slC = new QSlider(Qt::Horizontal); slC->setMaximum((int)sliderCmax); slC->setMinimum(1); slC->setValue(0.07*sliderCmax); settings->addWidget(labC); settings->addWidget(slC); QObject::connect(slC,SIGNAL(valueChanged(int)),plot,SLOT(setC(int))); QLabel *labD = new QLabel("Efektywnosc usmiercania ofiar przez\ndrapieznikow (0,1]"); QSlider *slD = new QSlider(Qt::Horizontal); slD->setMaximum((int)sliderDmax); slD->setMinimum(1); slD->setValue(0.008*sliderDmax); settings->addWidget(labD); settings->addWidget(slD); QObject::connect(slD,SIGNAL(valueChanged(int)),plot,SLOT(setD(int))); QLabel *labH = new QLabel("Krok czasowy (0,1]"); QSlider *slH = new QSlider(Qt::Horizontal); slH->setMaximum((int)sliderHmax); slH->setMinimum(1); slH->setValue(0.1*sliderHmax); settings->addWidget(labH); settings->addWidget(slH); QObject::connect(slH,SIGNAL(valueChanged(int)),plot,SLOT(setH(int))); QLabel *labN = new QLabel("Ilosc krokow (0,1000000]"); QSlider *slN = new QSlider(Qt::Horizontal); slN->setMaximum(100000); slN->setMinimum(1); slN->setValue(10000); settings->addWidget(labN); settings->addWidget(slN); QObject::connect(slN,SIGNAL(valueChanged(int)),plot,SLOT(setN(int))); QLabel *labX = new QLabel("Poczatkowa ilosc drapieznikow\n(0,10000]"); QSlider *slX = new QSlider(Qt::Horizontal); slX->setMaximum(1000); slX->setMinimum(1); slX->setValue(1); settings->addWidget(labX); settings->addWidget(slX); QObject::connect(slX,SIGNAL(valueChanged(int)),plot,SLOT(setX0(int))); QLabel *labY = new QLabel("Poczatkowa ilosc ofiar (0,10000]"); QSlider *slY = new QSlider(Qt::Horizontal); slY->setMaximum(10000); slY->setMinimum(1); slY->setValue(1000); settings->addWidget(labY); settings->addWidget(slY); QObject::connect(slY,SIGNAL(valueChanged(int)),plot,SLOT(setY0(int))); // ******************************************************************************** layout->addWidget(plot); layout->addLayout(settings); window->setLayout(layout); window->adjustSize(); window->setFixedWidth(900); window->show(); return app.exec(); }
void QtDensity::setupDisplay(void) { QWidget *window = new QWidget; window->setWindowTitle("Qt and RInside demo: density estimation"); QSpinBox *spinBox = new QSpinBox; QSlider *slider = new QSlider(Qt::Horizontal); spinBox->setRange(5, 200); slider->setRange(5, 200); QObject::connect(spinBox, SIGNAL(valueChanged(int)), slider, SLOT(setValue(int))); QObject::connect(slider, SIGNAL(valueChanged(int)), spinBox, SLOT(setValue(int))); spinBox->setValue(m_bw); QObject::connect(spinBox, SIGNAL(valueChanged(int)), this, SLOT(getBandwidth(int))); QLabel *cmdLabel = new QLabel("R command for random data creation"); QLineEdit *cmdEntry = new QLineEdit(m_cmd); QObject::connect(cmdEntry, SIGNAL(textEdited(QString)), this, SLOT(getRandomDataCmd(QString))); QObject::connect(cmdEntry, SIGNAL(editingFinished()), this, SLOT(runRandomDataCmd())); QGroupBox *kernelRadioBox = new QGroupBox("Density Estimation kernel"); QRadioButton *radio1 = new QRadioButton("&Gaussian"); QRadioButton *radio2 = new QRadioButton("&Epanechnikov"); QRadioButton *radio3 = new QRadioButton("&Rectangular"); QRadioButton *radio4 = new QRadioButton("&Triangular"); QRadioButton *radio5 = new QRadioButton("&Cosine"); radio1->setChecked(true); QVBoxLayout *vbox = new QVBoxLayout; vbox->addWidget(radio1); vbox->addWidget(radio2); vbox->addWidget(radio3); vbox->addWidget(radio4); vbox->addWidget(radio5); kernelRadioBox->setMinimumSize(260,140); kernelRadioBox->setMaximumSize(260,140); kernelRadioBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); kernelRadioBox->setLayout(vbox); QButtonGroup *kernelGroup = new QButtonGroup; kernelGroup->addButton(radio1, 0); kernelGroup->addButton(radio2, 1); kernelGroup->addButton(radio3, 2); kernelGroup->addButton(radio4, 3); kernelGroup->addButton(radio5, 4); QObject::connect(kernelGroup, SIGNAL(buttonClicked(int)), this, SLOT(getKernel(int))); m_svg = new QSvgWidget(); runRandomDataCmd(); // also calls plot() QGroupBox *estimationBox = new QGroupBox("Density estimation bandwidth (scaled by 100)"); QHBoxLayout *spinners = new QHBoxLayout; spinners->addWidget(spinBox); spinners->addWidget(slider); QVBoxLayout *topright = new QVBoxLayout; topright->addLayout(spinners); topright->addWidget(cmdLabel); topright->addWidget(cmdEntry); estimationBox->setMinimumSize(360,140); estimationBox->setMaximumSize(360,140); estimationBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); estimationBox->setLayout(topright); QHBoxLayout *upperlayout = new QHBoxLayout; upperlayout->addWidget(kernelRadioBox); upperlayout->addWidget(estimationBox); QHBoxLayout *lowerlayout = new QHBoxLayout; lowerlayout->addWidget(m_svg); QVBoxLayout *outer = new QVBoxLayout; outer->addLayout(upperlayout); outer->addLayout(lowerlayout); window->setLayout(outer); window->show(); }
int main( int argc, char** argv ) { // initialize the entire render system RenderSystem* render_system = RenderSystem::get(); QApplication app( argc, argv ); // make the render window RenderWidget* window = new RenderWidget( render_system ); window->setWindowTitle( "I hope this is not all black." ); QVBoxLayout* layout = new QVBoxLayout; layout->addWidget( window ); QPushButton* hide_button = new QPushButton( "hide" ); layout->addWidget( hide_button ); QPushButton* show_button = new QPushButton( "show" ); layout->addWidget( show_button ); QWidget container; container.setLayout( layout ); container.resize( 900, 600 ); container.show(); // Make a scene and show it in the window. Ogre::SceneManager* scene_manager = render_system->root()->createSceneManager( Ogre::ST_GENERIC ); Ogre::Entity* thing = scene_manager->createEntity( "thing", "rviz_cone.mesh" ); Ogre::SceneNode* node = scene_manager->getRootSceneNode()->createChildSceneNode(); node->attachObject( thing ); scene_manager->setAmbientLight( Ogre::ColourValue( .5, .5, .5 )); Ogre::Light* light = scene_manager->createLight( "light" ); light->setPosition( 20, 80, 50 ); Ogre::Camera* camera = scene_manager->createCamera( "SampleCam" ); camera->setPosition( Ogre::Vector3( 0, 0, 10 )); camera->lookAt( Ogre::Vector3( 0, 0, -300 )); camera->setNearClipDistance( 5 ); Ogre::Viewport* viewport = window->getRenderWindow()->addViewport( camera ); viewport->setBackgroundColour( Ogre::ColourValue( 0, 0, 1.0 )); camera->setAspectRatio( Ogre::Real( viewport->getActualWidth() ) / Ogre::Real( viewport->getActualHeight() )); // redraw every 33ms. QTimer timer; QObject::connect( &timer, SIGNAL(timeout()), window, SLOT(update()) ); timer.start( 33 ); RenderWidget window2( render_system ); window2.resize( 400, 400 ); window2.setWindowTitle( "I hope this is also not all black." ); window2.show(); hide_button->connect( hide_button, SIGNAL( clicked() ), &window2, SLOT( hide() )); show_button->connect( show_button, SIGNAL( clicked() ), &window2, SLOT( show() )); Ogre::Camera* camera2 = scene_manager->createCamera( "SampleCam2" ); camera2->setPosition( Ogre::Vector3( 0, 10, 0 )); camera2->setFixedYawAxis( false ); camera2->lookAt( Ogre::Vector3( 0, 0, 0 )); camera2->setNearClipDistance( 5 ); Ogre::Viewport* viewport2 = window2.getRenderWindow()->addViewport( camera2 ); viewport2->setBackgroundColour( Ogre::ColourValue( 0, 1.0, 0 )); camera2->setAspectRatio( Ogre::Real( viewport2->getActualWidth() ) / Ogre::Real( viewport2->getActualHeight() )); // redraw every 33ms. QTimer timer2; QObject::connect( &timer2, SIGNAL(timeout()), &window2, SLOT(update()) ); timer2.start( 33 ); // main loop return app.exec(); }
int main(int argc, char *argv[]) { XSqlQuery main; Q_INIT_RESOURCE(guiclient); QString username; QString databaseURL; QString passwd; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; bool haveEnhancedAuth= false; bool _enhancedAuth = false; bool havePasswd = false; bool forceWelcomeStub= false; qInstallMsgHandler(xTupleMessageOutput); QApplication app(argc, argv); app.setOrganizationDomain("xTuple.com"); app.setOrganizationName("xTuple"); app.setApplicationName("xTuple"); app.setApplicationVersion(_Version); #if QT_VERSION >= 0x040400 // This is the correct place for this call but on versions less // than 4.4 it causes a crash for an unknown reason so it is // called later on earlier versions. QCoreApplication::addLibraryPath(QString(".")); #endif #ifndef Q_WS_MACX QApplication::setWindowIcon(QIcon(":/images/icon32x32.png")); #endif app.processEvents(); if (argc > 1) { for (int intCounter = 1; intCounter < argc; intCounter++) { QString argument(argv[intCounter]); if (argument.contains("-databaseURL=", Qt::CaseInsensitive)) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive)) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.contains("-noAuth", Qt::CaseInsensitive)) { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive)) { haveEnhancedAuth = true; _enhancedAuth = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _enhancedAuth = false; } else if (argument.contains("-forceWelcomeStub", Qt::CaseInsensitive)) forceWelcomeStub = true; } } // Try and load a default translation file and install it // otherwise if we are non-english inform the user that translation are available bool checkLanguage = false; QLocale sysl = QLocale::system(); QTranslator defaultTranslator(&app); if (defaultTranslator.load(translationFile(sysl.name().toLower(), "default"))) app.installTranslator(&defaultTranslator); else if(!xtsettingsValue("LanguageCheckIgnore", false).toBool() && sysl.language() != QLocale::C && sysl.language() != QLocale::English) checkLanguage = translationFile(sysl.name().toLower(), "xTuple").isNull(); if (forceWelcomeStub || checkLanguage) { QTranslator * translator = new QTranslator(&app); if (translator->load(translationFile(sysl.name().toLower(), "welcome/wmsg"))) app.installTranslator(translator); welcomeStub wsdlg; wsdlg.checkBox->setChecked(xtsettingsValue("LanguageCheckIgnore", false).toBool()); wsdlg.exec(); xtsettingsSetValue("LanguageCheckIgnore", wsdlg.checkBox->isChecked()); } _splash = new QSplashScreen(); _splash->setPixmap(QPixmap(":/images/splashEmpty.png")); _evaluation = FALSE; if (!loggedIn) { ParameterList params; params.append("copyright", _Copyright); params.append("version", _Version); params.append("build", _Build.arg(__DATE__).arg(__TIME__)); params.append("setSearchPath", true); if (haveUsername) params.append("username", username); if (havePasswd) params.append("password", passwd); if (haveDatabaseURL) params.append("databaseURL", databaseURL); if (haveEnhancedAuth) params.append("enhancedAuth", _enhancedAuth); if (_evaluation) params.append("evaluation"); if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) params.append("login"); login2 newdlg(0, "", TRUE); newdlg.set(params, _splash); if(newdlg.result() != QDialog::Accepted) { if (newdlg.exec() == QDialog::Rejected) return -1; else { databaseURL = newdlg._databaseURL; username = newdlg.username(); __password = newdlg.password(); } } } // TODO: can/should we compose the splash screen on the fly from parts? QList<editionDesc> edition; edition << editionDesc( "Enterprise", ":/images/splashEnterprise.png", true, "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 4" " FROM pkghead" " WHERE pkghead_name IN ('xtmfg', 'xtprjaccnt', 'asset', 'assetdepn');" ) << editionDesc( "Manufacturing", ":/images/splashMfgEdition.png", true, "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 1" " FROM pkghead" " WHERE pkghead_name IN ('xtmfg');" ) << editionDesc( "Distribution", ":/images/splashDistEdition.png", true, "SELECT fetchMetricText('Application') = 'Standard';" ) << editionDesc( "PostBooks", ":/images/splashPostBooks.png", true, "SELECT fetchMetricText('Application') = 'PostBooks';" ) ; XSqlQuery metric; int editionIdx; // we'll use this after the loop for (editionIdx = 0; editionIdx < edition.size(); editionIdx++) { metric.exec(edition[editionIdx].queryString); if (metric.first() && metric.value(0).toBool()) break; } if (editionIdx >= edition.size()) editionIdx = edition.size(); // default to PostBooks _splash->setPixmap(QPixmap(edition[editionIdx].splashResource)); _Name = _Name.arg(edition[editionIdx].editionName); if (edition[editionIdx].shouldCheckLicense) { _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); // PostgreSQL changed the column "procpid" to just "pid" in 9.2.0+ Incident #21852 XSqlQuery checkVersion(QString("select compareversion('9.2.0');")); if(checkVersion.first()) { if(checkVersion.value("compareversion").toInt() > 0) { metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total" " FROM pg_stat_activity, pg_locks" " WHERE((database=datid)" " AND (classid=datid)" " AND (objsubid=2)" " AND (procpid = pg_backend_pid()));"); } else { metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total" " FROM pg_stat_activity, pg_locks" " WHERE((database=datid)" " AND (classid=datid)" " AND (objsubid=2)" " AND (pg_stat_activity.pid = pg_backend_pid()));"); } } int cnt = 50000; int tot = 50000; if(metric.first()) { cnt = metric.value("registered").toInt(); tot = metric.value("total").toInt(); } metric.exec("SELECT packageIsEnabled('drupaluserinfo') AS result;"); bool xtweb = false; if(metric.first()) xtweb = metric.value("result").toBool(); metric.exec("SELECT fetchMetricBool('ForceLicenseLimit') as metric_value;"); bool forceLimit = false; bool forced = false; if(metric.first()) forceLimit = metric.value("metric_value").toBool(); metric.exec("SELECT metric_value" " FROM metric" " WHERE(metric_name = 'RegistrationKey');"); bool checkPass = true; bool checkLock = false; bool expired = false; QString checkPassReason; QString rkey = ""; if(metric.first()) rkey = metric.value("metric_value").toString(); XTupleProductKey pkey(rkey); QString application; metric.exec("SELECT fetchMetricText('Application') as app;"); if(metric.first()) { application = metric.value("app").toString(); } if(pkey.valid() && (pkey.version() == 1 || pkey.version() == 2 || pkey.version() == 3)) { if(pkey.expiration() < QDate::currentDate()) { checkPass = false; checkPassReason = QObject::tr("<p>Your license has expired."); if(!pkey.perpetual()) { int daysTo = pkey.expiration().daysTo(QDate::currentDate()); if(daysTo > 30) { checkLock = true; expired = true; checkPassReason = QObject::tr("<p>Your xTuple license expired over 30 days ago, and this software will no longer function. Please contact xTuple immediately to reinstate your software."); } else checkPassReason = QObject::tr("<p>Attention: Your xTuple license has expired, and in %1 days this software will cease to function. Please make arrangements for immediate payment").arg(30 - daysTo); } else expired = true; } else if(application == "PostBooks" && pkey.users() == 1) { if(pkey.users() < cnt) { checkPass = false; checkPassReason = QObject::tr("<p>Multiple concurrent users of xTuple PostBooks require a license key. Please contact [email protected] to request a free license key for your local installation, or [email protected] to purchase additional users in the xTuple Cloud Service. <p>Thank you."); checkLock = forced = forceLimit; } } else if(pkey.users() != 0 && (pkey.users() < cnt || (!xtweb && (pkey.users() * 2 < tot)))) { checkPass = false; checkPassReason = QObject::tr("<p>You have exceeded the number of allowed concurrent users for your license."); checkLock = forced = forceLimit; } else { int daysTo = QDate::currentDate().daysTo(pkey.expiration()); if(!pkey.perpetual() && daysTo <= 15) { checkPass = false; checkPassReason = QObject::tr("<p>Please note: your xTuple license will expire in %1 days. You should already have received your renewal invoice; please contact xTuple at your earliest convenience.").arg(daysTo); } } } else { checkPass = false; checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid."); } if(!checkPass) { _splash->hide(); if (expired) { registrationKeyDialog newdlg(0, "", TRUE); if(newdlg.exec() == -1) { QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason); return 0; } } else if(checkLock) { QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason); if(!forced) return 0; } else { if(QMessageBox::critical(0, QObject::tr("Registration Key"), QObject::tr("%1\n<p>Would you like to continue anyway?").arg(checkPassReason), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No) return 0; } if(forced) checkPassReason.append(" FORCED!"); metric.exec("SELECT current_database() AS db," " fetchMetricText('DatabaseName') AS dbname," " fetchMetricText('remitto_name') AS name;"); QString db = ""; QString dbname = ""; QString name = ""; if(metric.first()) { db = metric.value("db").toString(); dbname = metric.value("dbname").toString(); name = metric.value("name").toString(); } QHttp *http = new QHttp(); QUrl url; url.setPath("/api/regviolation.php"); url.addQueryItem("key", QUrl::toPercentEncoding(rkey)); url.addQueryItem("error", QUrl::toPercentEncoding(checkPassReason)); url.addQueryItem("name", QUrl::toPercentEncoding(name)); url.addQueryItem("dbname", QUrl::toPercentEncoding(dbname)); url.addQueryItem("db", QUrl::toPercentEncoding(db)); url.addQueryItem("cnt", QString::number(cnt)); url.addQueryItem("tot", QString::number(tot)); url.addQueryItem("ver", _Version); http->setHost("www.xtuple.org"); http->get(url.toString()); if(forced) return 0; _splash->show(); } } bool disallowMismatch = false; bool shouldCheckForUpdates = false; metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'ServerVersion')"); if (!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) { int result = 0; metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'DisallowMismatchClientVersion')"); if (metric.first() && (metric.value("metric_value").toString() == "t")) { disallowMismatch = true; } metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'CheckForUpdates')"); if (metric.first()) { shouldCheckForUpdates = (metric.value("metric_value").toString() == "t" ? true : false); } if (shouldCheckForUpdates) { _splash->hide(); checkForUpdates newdlg(0,"", TRUE); result = newdlg.exec(); if (result == QDialog::Rejected) { return 0; } } else if (!shouldCheckForUpdates && disallowMismatch) { _splash->hide(); result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. The system has been configured to disallow " "access in this case.<p>Please contact your systems " "administrator.").arg(_Version), QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default ); return 0; } else { _splash->hide(); result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. If you continue some or all functionality may " "not work properly or at all. You may also cause other " "problems on the database.<p>Do you want to continue " "anyway?").arg(_Version), QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default ); if (result != QMessageBox::Yes) { return 0; } else { _splash->show(); } } } _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metrics = new Metrics(); _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _preferences = new Preferences(username); _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _privileges = new Privileges(); // Load the translator and set the locale from the User's preferences _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); XSqlQuery langq("SELECT * " "FROM usr, locale LEFT OUTER JOIN" " lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN" " country ON (locale_country_id=country_id) " "WHERE ( (usr_username=getEffectiveXtUser())" " AND (usr_locale_id=locale_id) );" ); if (langq.first()) { QStringList files; if (!langq.value("locale_lang_file").toString().isEmpty()) files << langq.value("locale_lang_file").toString(); QString langext; if (!langq.value("lang_abbr2").toString().isEmpty() && !langq.value("country_abbr").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString() + "_" + langq.value("country_abbr").toString().toLower(); } else if (!langq.value("lang_abbr2").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString(); } if(!langext.isEmpty()) { files << "qt"; files << "xTuple"; files << "openrpt"; files << "reports"; XSqlQuery pkglist("SELECT pkghead_name" " FROM pkghead" " WHERE packageIsEnabled(pkghead_name);"); while(pkglist.next()) files << pkglist.value("pkghead_name").toString(); } if (files.size() > 0) { QStringList notfound; QTranslator *translator = new QTranslator(&app); for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit) { if (DEBUG) qDebug("looking for %s", (*fit).toAscii().data()); if (translator->load(translationFile(langext, *fit))) { app.installTranslator(translator); qDebug("installed %s", (*fit).toAscii().data()); translator = new QTranslator(&app); } else { notfound << *fit; } } if (! notfound.isEmpty() && !_preferences->boolean("IngoreMissingTranslationFiles")) QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"), QObject::tr("<p>The Translation Dictionaries %1 " "cannot be loaded. Reverting " "to the default dictionary." ) .arg(notfound.join(QObject::tr(", ")))); } /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or lang#, depending on what information is available */ QString langAbbr = langq.value("lang_abbr2").toString(); QString cntryAbbr = langq.value("country_abbr").toString().toUpper(); if(cntryAbbr == "UK") cntryAbbr = "GB"; if (! langAbbr.isEmpty() && ! cntryAbbr.isEmpty()) QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr)); else if (! langAbbr.isEmpty()) QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString())); else if (langq.value("lang_qt_number").toInt() && langq.value("country_qt_number").toInt()) QLocale::setDefault( QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()), QLocale::Country(langq.value("country_qt_number").toInt()))); else QLocale::setDefault(QLocale::system()); qDebug("Locale set to language %s and country %s", QLocale().languageToString(QLocale().language()).toAscii().data(), QLocale().countryToString(QLocale().country()).toAscii().data()); } else if (langq.lastError().type() != QSqlError::NoError) { systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__); } qApp->processEvents(); QString key; // TODO: Add code to check a few locations - Hopefully done QString keypath; QString keyname; QString keytogether; #ifdef Q_WS_WIN keypath = _metrics->value("CCWinEncKey"); #elif defined Q_WS_MACX keypath = _metrics->value("CCMacEncKey"); #elif defined Q_WS_X11 keypath = _metrics->value("CCLinEncKey"); #endif if (keypath.isEmpty()) keypath = app.applicationDirPath(); if (! keypath.endsWith(QDir::separator())) keypath += QDir::separator(); keyname = _metrics->value("CCEncKeyName"); if (keyname.isEmpty()) { keyname = "xTuple.key"; keytogether = keypath + keyname; QFile kn(keytogether); if(!kn.exists()) keyname = "OpenMFG.key"; } keytogether = keypath + keyname; // qDebug("keytogether: %s", keytogether.toAscii().data()); QFile keyFile(keytogether); if(keyFile.exists()) { if(keyFile.open(QIODevice::ReadOnly)) { key = keyFile.readLine(1024); // strip off any newline characters key = key.trimmed(); } } omfgThis = 0; omfgThis = new GUIClient(databaseURL, username); omfgThis->_key = key; if (key.length() > 0) { _splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metricsenc = new Metricsenc(key); } initializePlugin(_preferences, _metrics, _privileges, omfgThis->username(), omfgThis->workspace()); // START code for updating the locale settings if they haven't been already XSqlQuery lc; lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';"); lc.first(); if(lc.value(0).toInt() == 0) { lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');"); lc.exec("SELECT locale_id from locale;"); while(lc.next()) { ParameterList params; params.append("mode","edit"); params.append("locale_id", lc.value(0)); sysLocale lcdlg; lcdlg.set(params); lcdlg.sSave(); } } // END code for updating locale settings QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows())); if (omfgThis->_singleWindow.isEmpty()) { omfgThis->setAttribute(Qt::WA_DeleteOnClose); omfgThis->show(); } // keep this synchronized with GUIClient and user.ui.h else if (omfgThis->_singleWindow == "woTimeClock") { ScriptToolbox sb(0); QWidget* newdlg = sb.openWindow("woTimeClock"); if(newdlg) { XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg); if(mw) { ParameterList params; params.append("captive"); mw->set(params); } newdlg->setAttribute(Qt::WA_DeleteOnClose); QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit())); newdlg->show(); } else {
int main( int argc, char **argv ) { QApplication app( argc, argv ); #ifndef QSA_NO_EDITOR QWidget widget; QSProject project; QVBoxLayout *vboxLayout = new QVBoxLayout(&widget); // some help text QLabel *help = new QLabel("Right-click on any of the buttons to edit " "its properties."); vboxLayout->addWidget(help); QWidget *hboxWidget = new QWidget; QHBoxLayout *hboxLayout = new QHBoxLayout(hboxWidget); vboxLayout->addWidget(hboxWidget); // create two sample widgets QGroupBox *lcdGroup = new QGroupBox( "lcd"); hboxLayout->addWidget(lcdGroup); QVBoxLayout *lcdgroupLayout = new QVBoxLayout(lcdGroup); QLCDNumber *lcd = new QLCDNumber; lcd->setObjectName("lcd"); lcdgroupLayout->addWidget(lcd); project.addObject(lcd); lcdgroupLayout->addWidget(new QLabel("Properties: <ul><li>value</li>" "<li>setHexMode()</li><li>...</li></ul>")); QGroupBox *editGroup = new QGroupBox( "edit"); hboxLayout->addWidget(editGroup); QVBoxLayout *editgroupLayout = new QVBoxLayout(editGroup); QLineEdit *edit = new QLineEdit; edit->setObjectName("edit"); edit->setText( "text" ); editgroupLayout->addWidget(edit); project.addObject(edit); editgroupLayout->addWidget(new QLabel("Properties: <ul><li>text</li><li>maxLength</li>" "<li>clear()</li><li>...</li></ul>")); QWidget *buttonWidget = new QWidget; QVBoxLayout *buttonLayout = new QVBoxLayout(buttonWidget); hboxLayout->addWidget(buttonWidget); // add script buttons ScriptButton *button1 = new ScriptButton(&project, "Increase Counter", 0, "button1"); buttonLayout->addWidget(button1); button1->setScriptCode( "Application.lcd.value++;" ); ScriptButton *button2 = new ScriptButton(&project, "Reset Counter", 0, "button2"); buttonLayout->addWidget(button2); button2->setScriptCode( "Application.lcd.value = 0;" ); ScriptButton *button3 = new ScriptButton(&project, "Convert to uppercase", 0, "button3"); buttonLayout->addWidget(button3); button3->setScriptCode( "Application.edit.text = Application.edit.text.upper();" ); QPushButton *button4 = new QPushButton("&Quit"); button4->setObjectName("button4"); buttonLayout->addStretch(-1); buttonLayout->addWidget(button4); QObject::connect(button4, SIGNAL(clicked()), &app, SLOT(quit())); // teach interpreter about widgets project.interpreter()->addWrapperFactory( new WidgetWrapperFactory() ); project.interpreter()->addObjectFactory( new QtNamespaceProvider() ); widget.show(); #else QMessageBox::information( 0, "Disabled feature", "QSA Editor has been disabled. Reconfigure to enable", QMessageBox::Ok ); #endif return app.exec(); }
void MainWindow::setGrip() { QLayoutIterator it = lay->iterator(); QLayoutItem *lastItem = NULL; for (;;){ QLayoutItem *item = it.current(); if (item == NULL) break; lastItem = item; if (++it == NULL) break; } if (lastItem == NULL) return; if (lastItem->layout() && (lastItem->layout() == h_lay)){ QLayoutIterator it = h_lay->iterator(); for (;;){ QLayoutItem *item = it.current(); if (item == NULL) break; QWidget *w = item->widget(); if (w && (w != m_grip)) return; if (++it == NULL) break; } } QWidget *oldWidget = NULL; QWidget *w = lastItem->widget(); if (m_grip){ delete m_grip; m_grip = NULL; } if (h_lay){ QLayoutIterator it = h_lay->iterator(); for (;;){ QLayoutItem *item = it.current(); if (item == NULL) break; oldWidget = item->widget(); if (oldWidget) break; if (++it == NULL) break; } delete h_lay; h_lay = NULL; it = lay->iterator(); for (;;){ QLayoutItem *item = it.current(); if (item == NULL) break; lastItem = item; if (++it == NULL) break; } if (lastItem) w = lastItem->widget(); } if (oldWidget && w){ int index = lay->findWidget(w); lay->insertWidget(index - 1, oldWidget); } if (w && (w->sizePolicy().verData() == QSizePolicy::Fixed) && !statusBar()->isVisible()){ w->reparent(this, QPoint()); w->reparent(main, QPoint()); h_lay = new QHBoxLayout(lay); h_lay->addWidget(w); h_lay->addSpacing(2); m_grip = new QSizeGrip(main); #ifdef WIN32 m_grip->installEventFilter(this); #endif m_grip->setFixedSize(m_grip->sizeHint()); h_lay->addWidget(m_grip, 0, AlignBottom); w->show(); m_grip->show(); } }
void tst_QColumnView::scrollTo() { QFETCH(bool, reverse); QFETCH(bool, giveFocus); if (reverse) qApp->setLayoutDirection(Qt::RightToLeft); ColumnView view; view.resize(200, 200); view.show(); view.scrollTo(QModelIndex(), QAbstractItemView::EnsureVisible); QCOMPARE(view.HorizontalOffset(), 0); TreeModel model; view.setModel(&model); view.scrollTo(QModelIndex(), QAbstractItemView::EnsureVisible); QModelIndex home; home = model.index(0, 0, home); home = model.index(0, 0, home); home = model.index(0, 0, home); view.scrollTo(home, QAbstractItemView::EnsureVisible); QModelIndex homeFile = model.index(0, 0, home); view.setRootIndex(home); QModelIndex index = model.index(0, 0, home); view.scrollTo(index, QAbstractItemView::EnsureVisible); QCOMPARE(view.HorizontalOffset(), 0); // Embedded requires that at least one widget have focus QWidget w; w.show(); if (giveFocus) view.setFocus(Qt::OtherFocusReason); else view.clearFocus(); QTRY_COMPARE(view.hasFocus(), giveFocus); // scroll to the right int level = 0; int last = view.HorizontalOffset(); while(model.hasChildren(index) && level < 5) { view.setCurrentIndex(index); QTest::qWait(ANIMATION_DELAY); view.scrollTo(index, QAbstractItemView::EnsureVisible); QTest::qWait(ANIMATION_DELAY); qApp->processEvents(); index = model.index(0, 0, index); level++; if (level >= 2) { if (!reverse) { QTRY_VERIFY(view.HorizontalOffset() < 0); QTRY_VERIFY(last > view.HorizontalOffset()); } else { QTRY_VERIFY(view.HorizontalOffset() > 0); QTRY_VERIFY(last < view.HorizontalOffset()); } } last = view.HorizontalOffset(); } // scroll to the left int start = level; while(index.parent().isValid() && index != view.rootIndex()) { view.setCurrentIndex(index); QTest::qWait(ANIMATION_DELAY); view.scrollTo(index, QAbstractItemView::EnsureVisible); index = index.parent(); if (start != level) { if (!reverse) QTRY_VERIFY(last < view.HorizontalOffset()); else QTRY_VERIFY(last > view.HorizontalOffset()); } level--; last = view.HorizontalOffset(); } // It shouldn't automatically steal focus if it doesn't have it QTRY_COMPARE(view.hasFocus(), giveFocus); // Try scrolling to something that is above the root index home = model.index(0, 0, QModelIndex()); QModelIndex temp = model.index(1, 0, home); home = model.index(0, 0, home); home = model.index(0, 0, home); view.setRootIndex(home); view.scrollTo(model.index(0, 0, home)); QTest::qWait(ANIMATION_DELAY); view.scrollTo(temp); }