QgsGeometryCheckerResultTab::QgsGeometryCheckerResultTab( QgisInterface *iface, QgsGeometryChecker *checker, QTabWidget *tabWidget, QWidget *parent )
  : QWidget( parent )
  , mTabWidget( tabWidget )
  , mIface( iface )
  , mChecker( checker )
{
  ui.setupUi( this );
  mErrorCount = 0;
  mFixedCount = 0;
  mCloseable = true;

  for ( const QString &layerId : mChecker->getContext()->featurePools.keys() )
  {
    QgsVectorLayer *layer = mChecker->getContext()->featurePools[layerId]->layer();
    QTreeWidgetItem *item = new QTreeWidgetItem( ui.treeWidgetMergeAttribute, QStringList() << layer->name() << "" );
    QComboBox *attribCombo = new QComboBox();
    for ( int i = 0, n = layer->fields().count(); i < n; ++i )
    {
      attribCombo->addItem( layer->fields().at( i ).name() );
    }
    attribCombo->setCurrentIndex( 0 );
    connect( attribCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( updateMergeAttributeIndices() ) );
    ui.treeWidgetMergeAttribute->setItemWidget( item, 1, attribCombo );
  }
  updateMergeAttributeIndices();

  connect( checker, &QgsGeometryChecker::errorAdded, this, &QgsGeometryCheckerResultTab::addError );
  connect( checker, &QgsGeometryChecker::errorUpdated, this, &QgsGeometryCheckerResultTab::updateError );
  connect( ui.tableWidgetErrors->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsGeometryCheckerResultTab::onSelectionChanged );
  connect( ui.buttonGroupSelectAction, static_cast<void ( QButtonGroup::* )( int )>( &QButtonGroup::buttonClicked ), this, [this]( int ) { QgsGeometryCheckerResultTab::highlightErrors(); } );
  connect( ui.pushButtonOpenAttributeTable, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::openAttributeTable );
  connect( ui.pushButtonFixWithDefault, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::fixErrorsWithDefault );
  connect( ui.pushButtonFixWithPrompt, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::fixErrorsWithPrompt );
  connect( ui.pushButtonErrorResolutionSettings, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::setDefaultResolutionMethods );
  connect( ui.checkBoxHighlight, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::highlightErrors );
  connect( QgsProject::instance(), static_cast<void ( QgsProject::* )( const QStringList & )>( &QgsProject::layersWillBeRemoved ), this, &QgsGeometryCheckerResultTab::checkRemovedLayer );
  connect( ui.pushButtonExport, &QAbstractButton::clicked, this, &QgsGeometryCheckerResultTab::exportErrors );

  bool allLayersEditable = true;
  for ( const QgsFeaturePool *featurePool : mChecker->getContext()->featurePools.values() )
  {
    if ( ( featurePool->layer()->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 )
    {
      allLayersEditable = false;
      break;
    }
  }
  if ( !allLayersEditable )
  {
    ui.pushButtonFixWithDefault->setEnabled( false );
    ui.pushButtonFixWithPrompt->setEnabled( false );
  }

  ui.progressBarFixErrors->setVisible( false );
  ui.tableWidgetErrors->horizontalHeader()->setSortIndicator( 0, Qt::AscendingOrder );
  ui.tableWidgetErrors->resizeColumnToContents( 0 );
  ui.tableWidgetErrors->resizeColumnToContents( 1 );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 2, QHeaderView::Stretch );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 3, QHeaderView::Stretch );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 4, QHeaderView::Stretch );
  ui.tableWidgetErrors->horizontalHeader()->setResizeMode( 5, QHeaderView::Stretch );
  // Not sure why, but this is needed...
  ui.tableWidgetErrors->setSortingEnabled( true );
  ui.tableWidgetErrors->setSortingEnabled( false );
}
//Reading ad writing parameters from/to selected widget to/from parameters container
void SynchronizeInterfaceWindow(QWidget *window, cParameterContainer *par,
		enumReadWrite mode)
{
	WriteLog("cInterface::SynchronizeInterface: QLineEdit", 3);
	//----------- QLineEdit -------------------
	{
		QList<QLineEdit *> widgetListLineEdit = window->findChildren<QLineEdit *>();
		QList<QLineEdit *>::iterator it;

		for (it = widgetListLineEdit.begin(); it != widgetListLineEdit.end(); ++it)
		{
			//qDebug() << "QLineEdit:" << (*it)->objectName() << " Type:" << (*it)->metaObject()->className() << endl;

			QString name = (*it)->objectName();
			QString className = (*it)->metaObject()->className();
			if (name.length() > 1
					&& (className == QString("QLineEdit") || className == QString("MyLineEdit")))
			{
				QLineEdit *lineEdit = *it;
				// QString text = lineEdit->text();
				//qDebug() << name << " - text: " << text << endl;

				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);
				//qDebug() << name << " - type: " << type << endl;

				if (className == QString("MyLineEdit"))
				{
					MyLineEdit *mylineedit = (MyLineEdit*) *it;
					mylineedit->AssignParameterContainer(par);
					mylineedit->AssingParameterName(parameterName);
				}

				//----- get vectors ------------
				if (type == QString("vect3") || type == QString("logvect3"))
				{
					char lastChar = (parameterName.at(parameterName.length() - 1)).toLatin1();
					QString nameVect = parameterName.left(parameterName.length() - 2);

					if (mode == read)
					{
						double value = systemData.locale.toDouble(lineEdit->text());
						//qDebug() << nameVect << " - " << lastChar << " axis = " << value << endl;
						CVector3 vect = par->Get<CVector3>(nameVect);

						switch (lastChar)
						{
							case 'x':
								vect.x = value;
								break;

							case 'y':
								vect.y = value;
								break;

							case 'z':
								vect.z = value;
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): edit field " << nameVect
										<< " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						par->Set(nameVect, vect);
					}
					else if (mode == write)
					{
						CVector3 vect = par->Get<CVector3>(nameVect);
						QString qtext;

						switch (lastChar)
						{
							case 'x':
								qtext = QString("%L1").arg(vect.x, 0, 'g', 16);
								break;

							case 'y':
								qtext = QString("%L1").arg(vect.y, 0, 'g', 16);
								break;

							case 'z':
								qtext = QString("%L1").arg(vect.z, 0, 'g', 16);
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): edit field " << nameVect
										<< " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						lineEdit->setText(qtext);
						lineEdit->setCursorPosition(0);
					}
				}

				//----- get vectors 4D  ------------
				if (type == QString("vect4"))
				{
					char lastChar = (parameterName.at(parameterName.length() - 1)).toLatin1();
					QString nameVect = parameterName.left(parameterName.length() - 2);

					if (mode == read)
					{
						double value = systemData.locale.toDouble(lineEdit->text());
						//qDebug() << nameVect << " - " << lastChar << " axis = " << value << endl;
						CVector4 vect = par->Get<CVector4>(nameVect);

						switch (lastChar)
						{
							case 'x':
								vect.x = value;
								break;

							case 'y':
								vect.y = value;
								break;

							case 'z':
								vect.z = value;
								break;

							case 'w':
								vect.w = value;
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): edit field " << nameVect
										<< " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						par->Set(nameVect, vect);
					}
					else if (mode == write)
					{
						CVector4 vect = par->Get<CVector4>(nameVect);
						QString qtext;

						switch (lastChar)
						{
							case 'x':
								qtext = QString("%L1").arg(vect.x, 0, 'g', 16);
								break;

							case 'y':
								qtext = QString("%L1").arg(vect.y, 0, 'g', 16);
								break;

							case 'z':
								qtext = QString("%L1").arg(vect.z, 0, 'g', 16);
								break;

							case 'w':
								qtext = QString("%L1").arg(vect.w, 0, 'g', 16);
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): edit field " << nameVect
										<< " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						lineEdit->setText(qtext);
						lineEdit->setCursorPosition(0);
					}
				}

				//---------- get double scalars --------
				else if (type == QString("edit") || type == QString("logedit"))
				{
					if (mode == read)
					{
						double value = systemData.locale.toDouble(lineEdit->text());
						par->Set(parameterName, value);
					}
					else if (mode == write)
					{
						double value = par->Get<double>(parameterName);
						lineEdit->setText(QString("%L1").arg(value, 0, 'g', 16));
						lineEdit->setCursorPosition(0);
					}
				}

				//----------- get texts ------------
				else if (type == QString("text"))
				{
					if (mode == read)
					{
						QString value = lineEdit->text();
						par->Set(parameterName, value);
					}
					else if (mode == write)
					{
						QString value = par->Get<QString>(parameterName);
						lineEdit->setText(value);
					}
				}
			}
		} //end foreach
	}

	WriteLog("cInterface::SynchronizeInterface: QDoubleSpinBox", 3);
	//------------ Double spin-box --------------
	{
		QList<QDoubleSpinBox *> widgetListDoubleSpinBox = window->findChildren<QDoubleSpinBox*>();
		QList<QDoubleSpinBox *>::iterator it;
		for (it = widgetListDoubleSpinBox.begin(); it != widgetListDoubleSpinBox.end(); ++it)
		{
			QString name = (*it)->objectName();
			//qDebug() << "QDoubleSpinBox:" << (*it)->objectName() << " Type:" << (*it)->metaObject()->className() << endl;
			QString className = (*it)->metaObject()->className();
			if (name.length() > 1
					&& (className == QString("QDoubleSpinBox") || className == QString("MyDoubleSpinBox")))
			{
				QDoubleSpinBox *spinbox = *it;

				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				if (className == QString("MyDoubleSpinBox"))
				{
					MyDoubleSpinBox *mydoublespinbox = (MyDoubleSpinBox*) *it;
					mydoublespinbox->AssignParameterContainer(par);
					mydoublespinbox->AssingParameterName(parameterName);
				}

				if (type == QString("spinbox") || type == QString("spinboxd"))
				{
					if (mode == read)
					{
						double value = spinbox->value();
						par->Set(parameterName, value);
					}
					else if (mode == write)
					{
						double value = par->Get<double>(parameterName);
						spinbox->setValue(value);
					}
				}
				else if (type == QString("spinbox3") || type == QString("spinboxd3"))
				{
					char lastChar = (parameterName.at(parameterName.length() - 1)).toLatin1();
					QString nameVect = parameterName.left(parameterName.length() - 2);
					if (mode == read)
					{
						double value = spinbox->value();
						CVector3 vect = par->Get<CVector3>(nameVect);

						switch (lastChar)
						{
							case 'x':
								vect.x = value;
								break;

							case 'y':
								vect.y = value;
								break;

							case 'z':
								vect.z = value;
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): " << type << " "
										<< nameVect << " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						par->Set(nameVect, vect);
					}
					else if (mode == write)
					{
						CVector3 vect = par->Get<CVector3>(nameVect);
						double value = 0;

						switch (lastChar)
						{
							case 'x':
								value = vect.x;
								break;

							case 'y':
								value = vect.y;
								break;

							case 'z':
								value = vect.z;
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): " << type << " "
										<< nameVect << " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						spinbox->setValue(value);
					}
				}
				else if (type == QString("spinbox4") || type == QString("spinboxd4"))
				{
					char lastChar = (parameterName.at(parameterName.length() - 1)).toLatin1();
					QString nameVect = parameterName.left(parameterName.length() - 2);
					if (mode == read)
					{
						double value = spinbox->value();
						CVector4 vect = par->Get<CVector4>(nameVect);

						switch (lastChar)
						{
							case 'x':
								vect.x = value;
								break;

							case 'y':
								vect.y = value;
								break;

							case 'z':
								vect.z = value;
								break;

							case 'w':
								vect.w = value;
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): " << type << " "
										<< nameVect << " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						par->Set(nameVect, vect);
					}
					else if (mode == write)
					{
						CVector4 vect = par->Get<CVector4>(nameVect);
						double value = 0;

						switch (lastChar)
						{
							case 'x':
								value = vect.x;
								break;

							case 'y':
								value = vect.y;
								break;

							case 'z':
								value = vect.z;
								break;

							case 'w':
								value = vect.w;
								break;

							default:
								qWarning() << "cInterface::SynchronizeInterfaceWindow(): " << type << " "
										<< nameVect << " has wrong axis name (is " << lastChar << ")" << endl;
								break;
						}
						spinbox->setValue(value);
					}
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: QSpinBox", 3);
	//------------ integer spin-box --------------
	{
		QList<QSpinBox *> widgetListDoubleSpinBox = window->findChildren<QSpinBox*>();
		QList<QSpinBox *>::iterator it;
		for (it = widgetListDoubleSpinBox.begin(); it != widgetListDoubleSpinBox.end(); ++it)
		{
			QString name = (*it)->objectName();
			//qDebug() << "QDoubleSpinBox:" << (*it)->objectName() << " Type:" << (*it)->metaObject()->className() << endl;
			QString className = (*it)->metaObject()->className();
			if (name.length() > 1
					&& (className == QString("QSpinBox") || className == QString("MySpinBox")))
			{
				QSpinBox *spinbox = *it;
				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				if (className == QString("MySpinBox"))
				{
					MySpinBox *myspinbox = (MySpinBox*) *it;
					myspinbox->AssignParameterContainer(par);
					myspinbox->AssingParameterName(parameterName);
				}

				if (type == QString("spinboxInt"))
				{
					if (mode == read)
					{
						int value = spinbox->value();
						par->Set(parameterName, value);
					}
					else if (mode == write)
					{
						int value = par->Get<int>(parameterName);
						spinbox->setValue(value);
					}
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: QCheckBox", 3);
	//checkboxes
	{
		QList<QCheckBox *> widgetListDoubleSpinBox = window->findChildren<QCheckBox*>();
		QList<QCheckBox *>::iterator it;
		for (it = widgetListDoubleSpinBox.begin(); it != widgetListDoubleSpinBox.end(); ++it)
		{
			QString name = (*it)->objectName();
			//qDebug() << "QCheckBox:" << (*it)->objectName() << " Type:" << (*it)->metaObject()->className() << endl;
			QString className = (*it)->metaObject()->className();
			if (name.length() > 1
					&& (className == QString("QCheckBox") || className == QString("MyCheckBox")))
			{
				QCheckBox *checkbox = *it;

				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				if (className == QString("MyCheckBox"))
				{
					MyCheckBox *mycheckbox = (MyCheckBox*) *it;
					mycheckbox->AssignParameterContainer(par);
					mycheckbox->AssingParameterName(parameterName);
				}

				if (type == QString("checkBox"))
				{
					if (mode == read)
					{
						bool value = checkbox->isChecked();
						par->Set(parameterName, value);
					}
					else if (mode == write)
					{
						bool value = par->Get<bool>(parameterName);
						checkbox->setChecked(value);
					}
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: QGroupBox", 3);
	//groupsBox with checkbox
	{
		QList<QGroupBox *> widgetListDoubleSpinBox = window->findChildren<QGroupBox*>();
		QList<QGroupBox *>::iterator it;
		for (it = widgetListDoubleSpinBox.begin(); it != widgetListDoubleSpinBox.end(); ++it)
		{
			QString name = (*it)->objectName();
			//qDebug() << "QGroupBox:" << (*it)->objectName() << " Type:" << (*it)->metaObject()->className() << endl;
			QString className = (*it)->metaObject()->className();
			if (name.length() > 1
					&& (className == QString("QGroupBox") || className == QString("MyGroupBox")))
			{
				QGroupBox *groupbox = *it;

				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				if (className == QString("MyGroupBox"))
				{
					MyGroupBox *mygroupbox = (MyGroupBox*) *it;
					mygroupbox->AssignParameterContainer(par);
					mygroupbox->AssingParameterName(parameterName);
				}

				if (type == QString("groupCheck"))
				{
					if (mode == read)
					{
						bool value = groupbox->isChecked();
						par->Set(parameterName, value);
					}
					else if (mode == write)
					{
						bool value = par->Get<bool>(parameterName);
						groupbox->setChecked(value);
					}
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: FileSelectWidget", 3);
	//---------- file select widgets -----------
	{
		QList<FileSelectWidget *> widgetListPushButton = window->findChildren<FileSelectWidget*>();
		QList<FileSelectWidget *>::iterator it;
		for (it = widgetListPushButton.begin(); it != widgetListPushButton.end(); ++it)
		{
			QString name = (*it)->objectName();
			// QString className = (*it)->metaObject()->className();
			if (name.length() > 1 && (*it)->metaObject()->className() == QString("FileSelectWidget"))
			{
				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				FileSelectWidget *fileSelectWidget = *it;
				fileSelectWidget->AssignParameterContainer(par);
				fileSelectWidget->AssingParameterName(parameterName);

				if (mode == read)
				{
					par->Set(parameterName, fileSelectWidget->GetPath());
				}
				else if (mode == write)
				{
					fileSelectWidget->SetPath(par->Get<QString>(parameterName));
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: MyColorButton", 3);
	//---------- color buttons -----------
	{
		QList<MyColorButton *> widgetListPushButton = window->findChildren<MyColorButton*>();
		QList<MyColorButton *>::iterator it;
		for (it = widgetListPushButton.begin(); it != widgetListPushButton.end(); ++it)
		{
			QString name = (*it)->objectName();
			// QString className = (*it)->metaObject()->className();
			if (name.length() > 1 && (*it)->metaObject()->className() == QString("MyColorButton"))
			{
				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				MyColorButton *colorButton = *it;
				colorButton->AssignParameterContainer(par);
				colorButton->AssingParameterName(parameterName);

				if (mode == read)
				{
					par->Set(parameterName, colorButton->GetColor());
				}
				else if (mode == write)
				{
					colorButton->setText("");
					colorButton->SetColor(par->Get<sRGB>(parameterName));
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: ColorPaletteWidget", 3);
	//---------- colorpalette -----------
	{
		QList<ColorPaletteWidget *> widgetListColorPalette =
				window->findChildren<ColorPaletteWidget*>();
		QList<ColorPaletteWidget *>::iterator it;
		for (it = widgetListColorPalette.begin(); it != widgetListColorPalette.end(); ++it)
		{
			QString name = (*it)->objectName();
			//qDebug() << "ColorPalette:" << (*it)->objectName() << " Type:" << (*it)->metaObject()->className() << endl;
			if (name.length() > 1 && (*it)->metaObject()->className() == QString("ColorPaletteWidget"))
			{
				ColorPaletteWidget *colorPaletteWidget = *it;

				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				colorPaletteWidget->AssignParameterContainer(par);
				colorPaletteWidget->AssingParameterName(parameterName);

				if (type == QString("colorpalette"))
				{
					if (mode == read)
					{
						cColorPalette palette = colorPaletteWidget->GetPalette();
						par->Set(parameterName, palette);
					}
					else if (mode == write)
					{
						cColorPalette palette = par->Get<cColorPalette>(parameterName);
						colorPaletteWidget->SetPalette(palette);
					}
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: QComboBox", 3);
	//combo boxes
	{
		QList<QComboBox *> widgetListPushButton = window->findChildren<QComboBox*>();
		QList<QComboBox *>::iterator it;
		for (it = widgetListPushButton.begin(); it != widgetListPushButton.end(); ++it)
		{
			QString name = (*it)->objectName();
			//qDebug() << "QComboBox:" << (*it)->objectName() << " Type:" << (*it)->metaObject()->className() << endl;
			if (name.length() > 1 && (*it)->metaObject()->className() == QString("QComboBox"))
			{
				QComboBox *comboBox = *it;

				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				if (type == QString("comboBox"))
				{
					if (mode == read)
					{
						int selection = comboBox->currentIndex();
						if (parameterName.left(7) == QString("formula"))
						{
							selection = fractalList[comboBox->itemData(selection).toInt()].internalID;
						}
						par->Set(parameterName, selection);
					}
					else if (mode == write)
					{
						int selection = par->Get<int>(parameterName);
						if (parameterName.left(7) == QString("formula"))
						{
							for (int i = 0; i < fractalList.size(); i++)
							{
								if (fractalList[i].internalID == selection)
								{
									selection = comboBox->findData(i);
									break;
								}
							}
						}
						comboBox->setCurrentIndex(selection);
					}
				}
			}
		}
	}

	WriteLog("cInterface::SynchronizeInterface: cMaterialSelector", 3);
	//---------- material selector -----------
	{
		QList<cMaterialSelector *> widgetListMaterialSelector =
				window->findChildren<cMaterialSelector*>();
		QList<cMaterialSelector *>::iterator it;
		for (it = widgetListMaterialSelector.begin(); it != widgetListMaterialSelector.end(); ++it)
		{
			QString name = (*it)->objectName();
			// QString className = (*it)->metaObject()->className();
			if (name.length() > 1 && (*it)->metaObject()->className() == QString("cMaterialSelector"))
			{
				QString type, parameterName;
				GetNameAndType(name, &parameterName, &type);

				cMaterialSelector *materialSelector = *it;
				materialSelector->AssignParameterContainer(par);
				materialSelector->AssingParameterName(parameterName);

				if (type == QString("materialselector"))
				{
					if (mode == read)
					{
						par->Set(parameterName, materialSelector->GetMaterialIndex());
					}
					else if (mode == write)
					{
						materialSelector->SetMaterialIndex(par->Get<int>(parameterName));
					}
				}
			}
		}
	}
	WriteLog("cInterface::SynchronizeInterface: Done", 3);
}
void ShaderParamsDialog::buildLayout()
{
   QPushButton *loadButton = NULL;
   QPushButton *saveButton = NULL;
   QPushButton *removeButton = NULL;
   QPushButton *applyButton = NULL;
   QHBoxLayout *topButtonLayout = NULL;
   QMenu *loadMenu = NULL;
   QMenu *saveMenu = NULL;
   QMenu *removeMenu = NULL;
   struct video_shader *menu_shader = NULL;
   struct video_shader *video_shader = NULL;
   struct video_shader *avail_shader = NULL;
   const char *shader_path = NULL;
   unsigned i;
   bool hasPasses = false;

   getShaders(&menu_shader, &video_shader);

   /* NOTE: For some reason, menu_shader_get() returns a COPY of what get_current_shader() gives us.
    * And if you want to be able to change shader settings/parameters from both the raster menu and
    * Qt at the same time... you must change BOTH or one will overwrite the other.
    *
    * AND, during a context reset, video_shader will be NULL but not menu_shader, so don't totally bail
    * just because video_shader is NULL.
    *
    * Someone please fix this mess.
    */

   if (video_shader)
   {
      avail_shader = video_shader;

      if (video_shader->passes == 0)
         setWindowTitle(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_SHADER_OPTIONS));
   }
   /* Normally we'd only use video_shader, but the vulkan driver returns a NULL shader when there
    * are zero passes, so just fall back to menu_shader.
    */
   else if (menu_shader)
   {
      avail_shader = menu_shader;

      if (menu_shader->passes == 0)
         setWindowTitle(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_SHADER_OPTIONS));
   }
   else
   {
      setWindowTitle(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_SHADER_OPTIONS));

      /* no shader is available yet, just keep retrying until it is */
      QTimer::singleShot(0, this, SLOT(buildLayout()));
      return;
   }

   clearLayout();

   /* Only check video_shader for the path, menu_shader seems stale... e.g. if you remove all the shader passes,
    * it still has the old path in it, but video_shader does not
    */
   if (video_shader)
   {
      if (!string_is_empty(video_shader->path))
      {
         shader_path = video_shader->path;
         setWindowTitle(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_CURRENT_SHADER)) + ": " + QFileInfo(shader_path).fileName());
      }
   }
   else if (menu_shader)
   {
      if (!string_is_empty(menu_shader->path))
      {
         shader_path = menu_shader->path;
         setWindowTitle(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_CURRENT_SHADER)) + ": " + QFileInfo(shader_path).fileName());
      }
   }
   else
      setWindowTitle(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_SHADER_OPTIONS));

   loadButton = new QPushButton(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_LOAD), this);
   saveButton = new QPushButton(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_SAVE), this);
   removeButton = new QPushButton(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_REMOVE), this);
   applyButton = new QPushButton(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_APPLY), this);

   loadMenu = new QMenu(loadButton);
   loadMenu->addAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_VIDEO_SHADER_PRESET), this, SLOT(onShaderLoadPresetClicked()));
   loadMenu->addAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_SHADER_ADD_PASS), this, SLOT(onShaderAddPassClicked()));

   loadButton->setMenu(loadMenu);

   saveMenu = new QMenu(saveButton);
   saveMenu->addAction(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_VIDEO_SHADER_PRESET_SAVE_AS)) + "...", this, SLOT(onShaderSavePresetAsClicked()));
   saveMenu->addAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_VIDEO_SHADER_PRESET_SAVE_CORE), this, SLOT(onShaderSaveCorePresetClicked()));
   saveMenu->addAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_VIDEO_SHADER_PRESET_SAVE_PARENT), this, SLOT(onShaderSaveParentPresetClicked()));
   saveMenu->addAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_VIDEO_SHADER_PRESET_SAVE_GAME), this, SLOT(onShaderSaveGamePresetClicked()));

   saveButton->setMenu(saveMenu);

   removeMenu = new QMenu(removeButton);

   /* When there are no passes, at least on first startup, it seems video_shader erroneously shows 1 pass, with an empty source file.
    * So we use menu_shader instead for that.
    */
   if (menu_shader)
   {
      for (i = 0; i < menu_shader->passes; i++)
      {
         QFileInfo fileInfo(menu_shader->pass[i].source.path);
         QString shaderBasename = fileInfo.completeBaseName();
         QAction *action = removeMenu->addAction(shaderBasename, this, SLOT(onShaderRemovePassClicked()));

         action->setData(i);
      }
   }

   removeMenu->addAction(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_SHADER_CLEAR_ALL_PASSES), this, SLOT(onShaderClearAllPassesClicked()));

   removeButton->setMenu(removeMenu);

   connect(applyButton, SIGNAL(clicked()), this, SLOT(onShaderApplyClicked()));

   topButtonLayout = new QHBoxLayout();
   topButtonLayout->addWidget(loadButton);
   topButtonLayout->addWidget(saveButton);
   topButtonLayout->addWidget(removeButton);
   topButtonLayout->addWidget(applyButton);

   m_layout->addLayout(topButtonLayout);

   /* NOTE: We assume that parameters are always grouped in order by the pass number, e.g., all parameters for pass 0 come first, then params for pass 1, etc. */
   for (i = 0; avail_shader && i < avail_shader->passes; i++)
   {
      QFormLayout *form = NULL;
      QGroupBox *groupBox = NULL;
      QFileInfo fileInfo(avail_shader->pass[i].source.path);
      QString shaderBasename = fileInfo.completeBaseName();
      QHBoxLayout *filterScaleHBoxLayout = NULL;
      QComboBox *filterComboBox = new QComboBox(this);
      QComboBox *scaleComboBox = new QComboBox(this);
      QToolButton *moveDownButton = NULL;
      QToolButton *moveUpButton = NULL;
      unsigned j = 0;

      /* Sometimes video_shader shows 1 pass with no source file, when there are really 0 passes. */
      if (shaderBasename.isEmpty())
         continue;

      hasPasses = true;

      filterComboBox->setProperty("pass", i);
      scaleComboBox->setProperty("pass", i);

      moveDownButton = new QToolButton(this);
      moveDownButton->setText("↓");
      moveDownButton->setProperty("pass", i);

      moveUpButton = new QToolButton(this);
      moveUpButton->setText("↑");
      moveUpButton->setProperty("pass", i);

      /* Can't move down if we're already at the bottom. */
      if (i < avail_shader->passes - 1)
         connect(moveDownButton, SIGNAL(clicked()), this, SLOT(onShaderPassMoveDownClicked()));
      else
         moveDownButton->setDisabled(true);

      /* Can't move up if we're already at the top. */
      if (i > 0)
         connect(moveUpButton, SIGNAL(clicked()), this, SLOT(onShaderPassMoveUpClicked()));
      else
         moveUpButton->setDisabled(true);

      for (;;)
      {
         QString filterLabel = getFilterLabel(j);

         if (filterLabel.isEmpty())
            break;

         if (j == 0)
            filterLabel = msg_hash_to_str(MENU_ENUM_LABEL_VALUE_DONT_CARE);

         filterComboBox->addItem(filterLabel, j);

         j++;
      }

      for (j = 0; j < 7; j++)
      {
         QString label;

         if (j == 0)
            label = msg_hash_to_str(MENU_ENUM_LABEL_VALUE_DONT_CARE);
         else
            label = QString::number(j) + "x";

         scaleComboBox->addItem(label, j);
      }

      filterComboBox->setCurrentIndex(static_cast<int>(avail_shader->pass[i].filter));
      scaleComboBox->setCurrentIndex(static_cast<int>(avail_shader->pass[i].fbo.scale_x));

      /* connect the signals only after the initial index is set */
      connect(filterComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onFilterComboBoxIndexChanged(int)));
      connect(scaleComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onScaleComboBoxIndexChanged(int)));

      form = new QFormLayout();
      groupBox = new QGroupBox(shaderBasename);
      groupBox->setLayout(form);
      groupBox->setProperty("pass", i);
      groupBox->setContextMenuPolicy(Qt::CustomContextMenu);

      connect(groupBox, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(onGroupBoxContextMenuRequested(const QPoint&)));

      m_layout->addWidget(groupBox);

      filterScaleHBoxLayout = new QHBoxLayout();
      filterScaleHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Preferred));
      filterScaleHBoxLayout->addWidget(new QLabel(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_FILTER)) + ":", this));
      filterScaleHBoxLayout->addWidget(filterComboBox);
      filterScaleHBoxLayout->addWidget(new QLabel(QString(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_SCALE)) + ":", this));
      filterScaleHBoxLayout->addWidget(scaleComboBox);
      filterScaleHBoxLayout->addSpacerItem(new QSpacerItem(20, 0, QSizePolicy::Preferred, QSizePolicy::Preferred));

      if (moveUpButton)
         filterScaleHBoxLayout->addWidget(moveUpButton);

      if (moveDownButton)
         filterScaleHBoxLayout->addWidget(moveDownButton);

      form->addRow("", filterScaleHBoxLayout);

      for (j = 0; j < avail_shader->num_parameters; j++)
      {
         struct video_shader_parameter *param = &avail_shader->parameters[j];

         if (param->pass != static_cast<int>(i))
            continue;

         addShaderParam(param, form);
      }
   }

   if (!hasPasses)
   {
      QLabel *noParamsLabel = new QLabel(msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_SHADER_NO_PASSES), this);
      noParamsLabel->setAlignment(Qt::AlignCenter);

      m_layout->addWidget(noParamsLabel);
   }

   m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));

   /* Why is this required?? The layout is corrupt without both resizes. */
   resize(width() + 1, height());
   show();
   resize(width() - 1, height());
}
Example #4
0
void EffectWidgetPrivate::autogenerateUi()
{
    Q_Q(EffectWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout(q);
    mainLayout->setMargin(0);
    const QList<Phonon::EffectParameter> parameters = effect->parameters();
    for (int i = 0; i < parameters.count(); ++i) {
        const EffectParameter &para = parameters.at(i);
        QVariant value = effect->parameterValue(para);
        QHBoxLayout *pLayout = new QHBoxLayout;
        mainLayout->addLayout(pLayout);

        QLabel *label = new QLabel(q);
        pLayout->addWidget(label);
        label->setText(para.name());
#ifndef QT_NO_TOOLTIP
        label->setToolTip(para.description());
#endif

        QWidget *control = 0;
        switch (int(para.type())) {
        case QVariant::String:
            {
                QComboBox *cb = new QComboBox(q);
                control = cb;
                if (value.type() == QVariant::Int) {
                    //value just defines the item index
                    for (int i = 0; i < para.possibleValues().count(); ++i) {
                        cb->addItem(para.possibleValues().at(i).toString());
                    }
                    cb->setCurrentIndex(value.toInt());
                    QObject::connect(cb, SIGNAL(currentIndexChanged(int)), q, SLOT(_k_setIntParameter(int)));
                } else {
                    for (int i = 0; i < para.possibleValues().count(); ++i) {
                        const QVariant &item = para.possibleValues().at(i);
                        cb->addItem(item.toString());
                        if (item == value) {
                            cb->setCurrentIndex(cb->count() - 1);
                        }
                    }
                    QObject::connect(cb, SIGNAL(currentIndexChanged(QString)), q, SLOT(_k_setStringParameter(QString)));
                }
            }
            break;
        case QVariant::Bool:
            {
                QCheckBox *cb = new QCheckBox(q);
                control = cb;
                cb->setChecked(value.toBool());
                QObject::connect(cb, SIGNAL(toggled(bool)), q, SLOT(_k_setToggleParameter(bool)));
            }
            break;
        case QVariant::Int:
            {
                QSpinBox *sb = new QSpinBox(q);
                control = sb;
                bool minValueOk = false;
                bool maxValueOk = false;
                const int minValue = para.minimumValue().toInt(&minValueOk);
                const int maxValue = para.maximumValue().toInt(&maxValueOk);

                sb->setRange(minValueOk ? minValue : DEFAULT_MIN_INT, maxValueOk ? maxValue : DEFAULT_MAX_INT);
                sb->setValue(value.toInt());
                QObject::connect(sb, SIGNAL(valueChanged(int)), q, SLOT(_k_setIntParameter(int)));
            }
            break;
        case QMetaType::Float:
        case QVariant::Double:
            {
                const qreal minValue = para.minimumValue().canConvert(QVariant::Double) ?
                    para.minimumValue().toReal() : DEFAULT_MIN;
                const qreal maxValue = para.maximumValue().canConvert(QVariant::Double) ?
                    para.maximumValue().toReal() : DEFAULT_MAX;

                if (minValue == -1. && maxValue == 1.) {
                    //Special case values between -1 and 1.0 to use a slider for improved usability
                    QSlider *slider = new QSlider(Qt::Horizontal, q);
                    control = slider;
                    slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE);
                    slider->setValue(int(SLIDER_RANGE * value.toReal()));
                    slider->setTickPosition(QSlider::TicksBelow);
                    slider->setTickInterval(TICKINTERVAL);
                    QObject::connect(slider, SIGNAL(valueChanged(int)), q, SLOT(_k_setSliderParameter(int)));
                } else {
                    double step = 0.1;
                    if (qAbs(maxValue - minValue) > 50)
                        step = 1.0;
                    QDoubleSpinBox *sb = new QDoubleSpinBox(q);
                    control = sb;
                    sb->setRange(minValue, maxValue);
                    sb->setValue(value.toDouble());
                    sb->setSingleStep(step);
                    QObject::connect(sb, SIGNAL(valueChanged(double)), q,
                        SLOT(_k_setDoubleParameter(double)));
                }
            }
            break;
        default:
            break;
        }

        if (control) {
#ifndef QT_NO_TOOLTIP
        control->setToolTip(para.description());
#endif
#ifndef QT_NO_SHORTCUT
            label->setBuddy(control);
#endif
            pLayout->addWidget(control);
            parameterForObject.insert(control, para);
        }
    }
}
AutoConfig::AutoConfig(QWidget *parent)
	: QWizard(parent)
{
	EnableThreadedMessageBoxes(true);

	calldata_t cd = {0};
	calldata_set_int(&cd, "seconds", 5);

	proc_handler_t *ph = obs_get_proc_handler();
	proc_handler_call(ph, "twitch_ingests_refresh", &cd);
	calldata_free(&cd);

	OBSBasic *main = reinterpret_cast<OBSBasic*>(parent);
	main->EnableOutputs(false);

	installEventFilter(CreateShortcutFilter());

	std::string serviceType;
	GetServiceInfo(serviceType, serviceName, server, key);
#ifdef _WIN32
	setWizardStyle(QWizard::ModernStyle);
#endif
	streamPage = new AutoConfigStreamPage();

	setPage(StartPage, new AutoConfigStartPage());
	setPage(VideoPage, new AutoConfigVideoPage());
	setPage(StreamPage, streamPage);
	setPage(TestPage, new AutoConfigTestPage());
	setWindowTitle(QTStr("Basic.AutoConfig"));
	setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

	obs_video_info ovi;
	obs_get_video_info(&ovi);

	baseResolutionCX = ovi.base_width;
	baseResolutionCY = ovi.base_height;

	/* ----------------------------------------- */
	/* check to see if Twitch's "auto" available */

	OBSData twitchSettings = obs_data_create();
	obs_data_release(twitchSettings);

	obs_data_set_string(twitchSettings, "service", "Twitch");

	obs_properties_t *props = obs_get_service_properties("rtmp_common");
	obs_properties_apply_settings(props, twitchSettings);

	obs_property_t *p = obs_properties_get(props, "server");
	const char *first = obs_property_list_item_string(p, 0);
	twitchAuto = strcmp(first, "auto") == 0;

	obs_properties_destroy(props);

	/* ----------------------------------------- */
	/* load service/servers                      */

	customServer = serviceType == "rtmp_custom";

	QComboBox *serviceList = streamPage->ui->service;

	if (!serviceName.empty()) {
		serviceList->blockSignals(true);

		int count = serviceList->count();
		bool found = false;

		for (int i = 0; i < count; i++) {
			QString name = serviceList->itemText(i);

			if (name == serviceName.c_str()) {
				serviceList->setCurrentIndex(i);
				found = true;
				break;
			}
		}

		if (!found) {
			serviceList->insertItem(0, serviceName.c_str());
			serviceList->setCurrentIndex(0);
		}

		serviceList->blockSignals(false);
	}

	streamPage->UpdateServerList();
	streamPage->UpdateKeyLink();
	streamPage->lastService.clear();

	if (!customServer) {
		QComboBox *serverList = streamPage->ui->server;
		int idx = serverList->findData(QString(server.c_str()));
		if (idx == -1)
			idx = 0;

		serverList->setCurrentIndex(idx);
	} else {
		streamPage->ui->customServer->setText(server.c_str());
		int idx = streamPage->ui->service->findData(
				QVariant((int)ListOpt::Custom));
		streamPage->ui->service->setCurrentIndex(idx);
	}

	if (!key.empty())
		streamPage->ui->key->setText(key.c_str());

	int bitrate = config_get_int(main->Config(), "SimpleOutput", "VBitrate");
	streamPage->ui->bitrate->setValue(bitrate);
	streamPage->ServiceChanged();

	TestHardwareEncoding();
	if (!hardwareEncodingAvailable) {
		delete streamPage->ui->preferHardware;
		streamPage->ui->preferHardware = nullptr;
	} else {
		/* Newer generations of NVENC have a high enough quality to
		 * bitrate ratio that if NVENC is available, it makes sense to
		 * just always prefer hardware encoding by default */
		bool preferHardware = nvencAvailable ||
		                      os_get_physical_cores() <= 4;
		streamPage->ui->preferHardware->setChecked(preferHardware);
	}

	setOptions(0);
	setButtonText(QWizard::FinishButton,
			QTStr("Basic.AutoConfig.ApplySettings"));
	setButtonText(QWizard::BackButton, QTStr("Back"));
	setButtonText(QWizard::NextButton, QTStr("Next"));
	setButtonText(QWizard::CancelButton, QTStr("Cancel"));
}
Example #6
0
void ShaderProgram::setupParameterUI(QWidget* parentWidget)
{
    QFormLayout* layout = new QFormLayout(parentWidget);
    QList<QPair<ShaderParam,QVariant> > paramsOrdered;
    for (auto p = m_params.begin(); p != m_params.end(); ++p)
    {
        paramsOrdered.push_back(qMakePair(p.key(), p.value()));
    }
    qSort(paramsOrdered.begin(), paramsOrdered.end(), paramOrderingLess);
    for (int i = 0; i < paramsOrdered.size(); ++i)
    {
        QWidget* edit = 0;
        const ShaderParam& parDesc = paramsOrdered[i].first;
        const QVariant& parValue = paramsOrdered[i].second;
        switch (parDesc.type)
        {
            case ShaderParam::Float:
                {
                    bool expScaling = parDesc.kvPairs.value("scaling", "exponential").
                                      startsWith("exp");
                    double speed = parDesc.kvPairs.value("speed", "1").toDouble();
                    if (speed == 0)
                        speed = 1;
                    DragSpinBox* spin = new DragSpinBox(expScaling, speed, parentWidget);
                    double min = parDesc.getDouble("min", 0);
                    double max = parDesc.getDouble("max", 100);
                    if (expScaling)
                    {
                        // Prevent min or max == 0 for exp scaling which would be invalid
                        if (max == 0) max = 100;
                        if (min == 0) min = max > 0 ? 1e-8 : -1e-8;
                        spin->setDecimals((int)floor(std::max(0.0, -log(min)/log(10.0)) + 0.5) + 2);
                    }
                    else
                    {
                        double m = std::max(fabs(min), fabs(max));
                        spin->setDecimals((int)floor(std::max(0.0, -log(m)/log(10.0)) + 0.5) + 2);
                    }
                    spin->setMinimum(min);
                    spin->setMaximum(max);
                    spin->setValue(parValue.toDouble());
                    connect(spin, SIGNAL(valueChanged(double)),
                            this, SLOT(setUniformValue(double)));
                    edit = spin;
                }
                break;
            case ShaderParam::Int:
                if (parDesc.kvPairs.contains("enum"))
                {
                    // Parameter is an enumeration variable
                    QComboBox* box = new QComboBox(parentWidget);
                    QStringList names = parDesc.kvPairs.value("enum").split('|');
                    box->insertItems(0, names);
                    box->setCurrentIndex(parValue.toInt());
                    connect(box, SIGNAL(currentIndexChanged(int)),
                            this, SLOT(setUniformValue(int)));
                    edit = box;
                }
                else
                {
                    // Parameter is a freely ranging integer
                    QSpinBox* spin = new QSpinBox(parentWidget);
                    spin->setMinimum(parDesc.getInt("min", 0));
                    spin->setMaximum(parDesc.getInt("max", 100));
                    spin->setValue(parValue.toInt());
                    connect(spin, SIGNAL(valueChanged(int)),
                            this, SLOT(setUniformValue(int)));
                    edit = spin;
                }
                break;
            default:
                // FIXME
                continue;
        }
Example #7
0
void plotWindow::setupPlotWindow()
{
  plot = new QGraphicsView(this);
  plot->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
  plot->setScene(&plotdata);
  QWidget *centralWidget = new QWidget;
  QVBoxLayout *centralLayout = new QVBoxLayout;
  QHBoxLayout *topContainerLayout = new QHBoxLayout;
  QGridLayout *topLayout = new QGridLayout;
  centralWidget->setLayout(centralLayout);
  const int margin = centralLayout->margin();
  centralLayout->setMargin(0);
  centralLayout->addLayout(topContainerLayout);
  centralLayout->addWidget(plot);
  topContainerLayout->setMargin(margin);
  topContainerLayout->addLayout(topLayout);
  topContainerLayout->addStretch();

  QLabel *matfileLabel = new QLabel("MAT file");
  QLabel *xvarLabel = new QLabel("X Coordinate");
  QLabel *yvarLabel = new QLabel("Y Coordinate");
  QLabel *ptlabelLabel = new QLabel("LABEL");
  QLabel *dimLabel = new QLabel("DIM");

  matfile = new QLineEdit;
  matfile->setReadOnly(true);
  QAction *matfileAct = new QAction(QIcon(":/res/images/cr16-action-fileopen.png"), tr("&Open"), this);
  QToolButton *matfileButton = new QToolButton();
  matfileButton->setDefaultAction(matfileAct);
  connect(matfileAct, SIGNAL(triggered()), this, SLOT(open()));

  xvar = new QComboBox;
  yvar = new QComboBox;
  ptlabel = new QSpinBox;
  dim = new QSpinBox;

  plotSelect = new QListWidget;
  plotSelect->setSelectionMode(QAbstractItemView::SingleSelection);
  QVBoxLayout *dockLayout = new QVBoxLayout;
  QHBoxLayout *buttonsLayout = new QHBoxLayout;
  QWidget     *dockWidget = new QWidget;
  QAction     *removePlotAct = new QAction(QIcon(":/res/images/cr16-action-eraser.png"), "Remove Selected", this);
  QToolButton *removePlotButton = new QToolButton;
  removePlotButton->setDefaultAction(removePlotAct);
  connect(removePlotAct, SIGNAL(triggered()), this, SLOT(removePlot()));

  QAction     *colorizePlotAct = new QAction(QIcon(":/res/images/cr16-action-colorize.png"), "Change Color", this);
  QToolButton *colorizePlotButton = new QToolButton;
  colorizePlotButton->setDefaultAction(colorizePlotAct);
  connect(colorizePlotAct, SIGNAL(triggered()), this, SLOT(colorizePlot()));

  dockWidget->setLayout(dockLayout);
  dockLayout->setMargin(0);
  dockLayout->addSpacing(margin);
  dockLayout->addLayout(buttonsLayout);
  dockLayout->addWidget(plotSelect);
  buttonsLayout->addWidget(removePlotButton);
  buttonsLayout->addWidget(colorizePlotButton);

  QAction *addPlotAct = new QAction(QIcon(":/res/images/cr16-action-add.png"), tr("Add Plot"), this);
  QToolButton *addPlotButton = new QToolButton();
  addPlotButton->setDefaultAction(addPlotAct);
  connect(addPlotAct, SIGNAL(triggered()), this, SLOT(addPlot()));

  QAction *clearAllPlotAct = new QAction(QIcon(":/res/images/cr16-action-remove.png"), tr("Clear All"), this);
  QToolButton *clearAllPlotButton = new QToolButton();
  clearAllPlotButton->setDefaultAction(clearAllPlotAct);
  connect(clearAllPlotAct, SIGNAL(triggered()), this, SLOT(clearPlot()));

  QAction *printAct = new QAction(QIcon(":/res/images/cr16-action-fileprint.png"), tr("Print"), this);
  QToolButton *printButton = new QToolButton();
  printButton->setDefaultAction(printAct);
  connect(printAct, SIGNAL(triggered()), this, SLOT(print()));

  QAction *exportSvgAct = new QAction(QIcon(":/res/images/cr16-action-svg-export.png"), tr("Export to SVG"), this);
  QToolButton *exportSvgButton = new QToolButton();
  exportSvgButton->setDefaultAction( exportSvgAct );
  connect( exportSvgAct, SIGNAL(triggered()), this, SLOT(exportSvg()) );
  
  QComboBox* xyLog = new QComboBox;
  xyLog->insertItem(0, "Linear");
  xyLog->insertItem(1, "SemiLogX");
  xyLog->insertItem(2, "SemiLogY");
  xyLog->insertItem(3, "LogLog");
  xyLog->setCurrentIndex(0);
  connect( xyLog, SIGNAL(currentIndexChanged(int)), &plotdata, SLOT(setAxes(int)) );

  this->addWidget(dockWidget);
  this->addWidget(centralWidget);

  topLayout->addWidget(matfileLabel, 0, 0);
  topLayout->addWidget(xvarLabel, 0, 2);
  topLayout->addWidget(yvarLabel, 0, 3);
  topLayout->addWidget(ptlabelLabel, 0, 4);
  topLayout->addWidget(dimLabel, 0, 5);
  topLayout->addWidget(matfile, 1, 0);
  topLayout->addWidget(matfileButton, 1, 1);
  topLayout->addWidget(xvar, 1, 2);
  topLayout->addWidget(yvar, 1, 3);
  topLayout->addWidget(ptlabel, 1, 4);
  topLayout->addWidget(dim, 1, 5);
  topLayout->addWidget(addPlotButton, 1, 6);
  topLayout->addWidget(clearAllPlotButton, 1, 7);
  topLayout->addWidget(printButton, 1, 8);
  topLayout->addWidget(exportSvgButton, 1, 9 );
  topLayout->addWidget(xyLog, 2, 0 );

  plot->setMinimumSize(plot->mapFromScene(plotdata.sceneRect()).boundingRect().size()*1.1 +
                       QSize(2*plot->frameWidth(), 2*plot->frameWidth()));
}
Example #8
0
void OpenconnectAuthWidget::processAuthForm(struct oc_auth_form *form)
{
    Q_D(OpenconnectAuthWidget);
    deleteAllFromLayout(d->ui.loginBoxLayout);
    if (form->banner) {
        addFormInfo(QLatin1String("dialog-information"), form->banner);
    }
    if (form->message) {
        addFormInfo(QLatin1String("dialog-information"), form->message);
    }
    if (form->error) {
        addFormInfo(QLatin1String("dialog-error"), form->error);
    }

    struct oc_form_opt *opt;
    QFormLayout *layout = new QFormLayout();
    QSizePolicy policy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    bool focusSet = false;
    for (opt = form->opts; opt; opt = opt->next) {
        if (opt->type == OC_FORM_OPT_HIDDEN || IGNORE_OPT(opt)) {
            continue;
        }
        QLabel *text = new QLabel(this);
        text->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
        text->setText(QString(opt->label));
        QWidget *widget = 0;
        const QString key = QString("form:%1:%2").arg(QLatin1String(form->auth_id)).arg(QLatin1String(opt->name));
        const QString value = d->secrets.value(key);
        if (opt->type == OC_FORM_OPT_PASSWORD || opt->type == OC_FORM_OPT_TEXT) {
            PasswordField *le = new PasswordField(this);
            le->setText(value);
            if (opt->type == OC_FORM_OPT_PASSWORD) {
                le->setPasswordModeEnabled(true);
            }
            if (!focusSet && le->text().isEmpty()) {
                le->setFocus(Qt::OtherFocusReason);
                focusSet = true;
            }
            widget = qobject_cast<QWidget*>(le);
        } else if (opt->type == OC_FORM_OPT_SELECT) {
            QComboBox *cmb = new QComboBox(this);
            struct oc_form_opt_select *sopt = reinterpret_cast<oc_form_opt_select *>(opt);
            for (int i = 0; i < sopt->nr_choices; i++) {
                cmb->addItem(QString::fromUtf8(FORMCHOICE(sopt, i)->label), QString::fromUtf8(FORMCHOICE(sopt, i)->name));
                if (value == QString::fromUtf8(FORMCHOICE(sopt, i)->name)) {
                    cmb->setCurrentIndex(i);
                    if (sopt == AUTHGROUP_OPT(form) && i != AUTHGROUP_SELECTION(form)) {
                        QTimer::singleShot(0, this, &OpenconnectAuthWidget::formGroupChanged);
                    }
                }
            }
            if (sopt == AUTHGROUP_OPT(form)) {
                connect(cmb, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &OpenconnectAuthWidget::formGroupChanged);
            }
            widget = qobject_cast<QWidget*>(cmb);
        }
        if (widget) {
            widget->setProperty("openconnect_opt", (quintptr)opt);
            widget->setSizePolicy(policy);
            layout->addRow(text, widget);
        }
    }
    d->ui.loginBoxLayout->addLayout(layout);
    d->passwordFormIndex = d->ui.loginBoxLayout->count() - 1;

    QDialogButtonBox *box = new QDialogButtonBox(this);
    QPushButton *btn = box->addButton(QDialogButtonBox::Ok);
    btn->setText(i18n("Login"));
    btn->setDefault(true);
    d->ui.loginBoxLayout->addWidget(box);
    box->setProperty("openconnect_form", (quintptr)form);

    connect(box, &QDialogButtonBox::accepted, this, &OpenconnectAuthWidget::formLoginClicked);
}
Example #9
0
CarMainWindow::CarMainWindow()
    : base_class()
    , ui(new Ui_MainWindow())
    , m_server("http://carcomm.cstimming.de/")
//    , m_server("http://localhost:3000/")
    , m_gpsDevice(NULL)
    , m_sliceSender(new SliceSender(m_server, this))
    , m_mapViewer(NULL) // must be initialized after setupUi()!
{
    ui->setupUi(this);
    setGpsReceiverStatus(cs::BAD);

    m_mapViewer = new MapViewer(ui->webView, m_server, this);

    // Set the date to now
    ui->dateTimeEdit->setDateTime(QDateTime::currentDateTime());

    // Fill the list of available time intervals
    QComboBox* comboBox = ui->comboBoxInterval;
    comboBox->addItem("1 Year", QVariant(525600));
    comboBox->addItem("6 Weeks", QVariant(60480));
    comboBox->addItem("1 Week", QVariant(10080));
    comboBox->addItem("1 Day", QVariant(1440));
    comboBox->addItem("2 Hours", QVariant(120));
    comboBox->addItem("15 Minutes", QVariant(15));
    comboBox->addItem("5 Minutes", QVariant(5));
    comboBox->setCurrentIndex(comboBox->findText("1 Week"));

    // Fill the list of COM ports
    comboBox = ui->comboBoxPort;
#ifdef Q_OS_WIN32
    for (int i = 1; i <= 8; ++i)
        comboBox->addItem("COM" + QString::number(i));
    comboBox->setCurrentIndex(comboBox->findText("COM4"));
#else
    comboBox->addItem("/dev/ttyACM0");
    for (int i = 0; i <= 4; ++i)
        comboBox->addItem("/dev/ttyUSB" + QString::number(i));
    comboBox->setCurrentIndex(comboBox->findText("/dev/ttyUSB0"));
#endif

    // Fill the list of baud rates
    comboBox = ui->comboBoxBaudrate;
    comboBox->addItem("1200", QVariant(1200));
    comboBox->addItem("2400", QVariant(2400));
    comboBox->addItem("4800", QVariant(4800));
    comboBox->addItem("9600", QVariant(9600));
    comboBox->addItem("14400", QVariant(14400));
    comboBox->addItem("38400", QVariant(38400));
    comboBox->addItem("57600", QVariant(57600));
    comboBox->addItem("115200", QVariant(115200));
    comboBox->setCurrentIndex(comboBox->findData(QVariant(38400)));

#if 0 // 1 //defined(Q_WS_S60)
    ui->groupBoxCurrentPos->setVisible(false);
    ui->groupBoxSerial->setVisible(false);
#endif

    // Signal/slots of SliceSender
    connect(m_sliceSender, SIGNAL(showMessage( const QString &, int)),
            statusBar(), SLOT(showMessage( const QString &, int)));
    connect(ui->actionTransmitPositionMessages, SIGNAL(triggered(bool)),
            m_sliceSender, SLOT(setAutoSendData(bool)));
    m_sliceSender->setAutoSendData(ui->actionTransmitPositionMessages->isChecked());
    connect(ui->buttonSendData, SIGNAL(clicked()),
            m_sliceSender, SLOT(sendDataNow()));
    connect(m_sliceSender, SIGNAL(showStatus(cs::Status)),
            this, SLOT(setSliceSenderStatus(cs::Status)));

    // Signal/slots of MapViewer
    connect(ui->actionAutoReloadMap, SIGNAL(triggered(bool)),
            m_mapViewer, SLOT(setAutoReloadWays(bool)));
    m_mapViewer->setAutoReloadWays(ui->actionAutoReloadMap->isChecked());
    connect(ui->buttonReload, SIGNAL(clicked()),
            m_mapViewer, SLOT(reloadWays()));
    connect(ui->actionResetMap, SIGNAL(triggered()),
            m_mapViewer, SLOT(reset()));
    on_comboBoxInterval_currentIndexChanged(ui->comboBoxInterval->currentIndex());
    connect(m_mapViewer, SIGNAL(showStatus(cs::Status)),
            this, SLOT(setMapViewerStatus(cs::Status)));
}
QWidget* ConstraintTag::createWidget(QList<Tag *> tags, QWidget *parent)
{
    // === Create Widget ===
    QWidget* base = new QWidget(parent);
    QHBoxLayout* horLayout = new QHBoxLayout();
    QStringList comboboxItems = QStringList() << tr("ignore") << tr("local") << tr("global");

    QVBoxLayout* posLayout = new QVBoxLayout();
    posLayout->setSpacing(0);
    posLayout->setContentsMargins(0,0,0,0);
    QComboBox* posComboBox = new QComboBox(base);
    posComboBox->addItems(comboboxItems);
    posLayout->addWidget(posComboBox);
    QCheckBox* affectXCB = new QCheckBox("x", base);
    QCheckBox* affectYCB = new QCheckBox("y", base);
    QHBoxLayout* l = new QHBoxLayout();
    l->setContentsMargins(0,0,0,0);
    l->setSpacing(0);
    l->addWidget(affectXCB);
    l->addWidget(affectYCB);
    posLayout->addLayout(l);
    posLayout->addStretch();
    ObjectEdit* posObject = new ObjectEdit(base);
    posObject->setProject(tags.first()->owner()->project());
    posLayout->addWidget(posObject);

    QVBoxLayout* rotLayout = new QVBoxLayout();
    rotLayout->setSpacing(0);
    rotLayout->setContentsMargins(0,0,0,0);
    QComboBox* rotComboBox = new QComboBox(base);
    rotComboBox->addItems(comboboxItems);
    rotLayout->addWidget(rotComboBox);
    rotLayout->addStretch();
    ObjectEdit* rotObject = new ObjectEdit(base);
    rotObject->setProject(tags.first()->owner()->project());
    rotLayout->addWidget(rotObject);

    QVBoxLayout* scaleLayout = new QVBoxLayout();
    scaleLayout->setSpacing(0);
    scaleLayout->setContentsMargins(0,0,0,0);
    QComboBox* scaleComboBox = new QComboBox(base);
    scaleComboBox->addItems(comboboxItems);
    scaleLayout->addWidget(scaleComboBox);
    scaleLayout->addStretch();
    ObjectEdit* scaleObject = new ObjectEdit(base);
    scaleObject->setProject(tags.first()->owner()->project());
    scaleLayout->addWidget(scaleObject);

    horLayout->addLayout(posLayout);
    horLayout->addLayout(rotLayout);
    horLayout->addLayout(scaleLayout);
    // === end create Widget ===

    // === define update function ===
    auto update = [=]() {

        posComboBox->blockSignals(true);
        posObject->blockSignals(true);
        affectXCB->blockSignals(true);
        affectYCB->blockSignals(true);
        rotComboBox->blockSignals(true);
        rotObject->blockSignals(true);
        scaleComboBox->blockSignals(true);
        scaleObject->blockSignals(true);

        bool pModeDifference = false;
        bool affectXDifference = false;
        bool affectYDifference = false;
        bool pIdDifference = false;
        bool rModeDifference = false;
        bool rIdDifference = false;
        bool sModeDifference = false;
        bool sIdDifference = false;

        Mode pMode = ((ConstraintTag*) tags.first())->_positionMode;
        bool affectX = ((ConstraintTag*) tags.first())->_affectX;
        bool affectY = ((ConstraintTag*) tags.first())->_affectY;
        quint64 pId = ((ConstraintTag*) tags.first())->_posId;
        bool hasPId = ((ConstraintTag*) tags.first())->_hasPosId;
        Mode rMode = ((ConstraintTag*) tags.first())->_rotationMode;
        quint64 rId = ((ConstraintTag*) tags.first())->_rotId;
        bool hasRId = ((ConstraintTag*) tags.first())->_hasRotId;
        Mode sMode = ((ConstraintTag*) tags.first())->_scalationMode;
        quint64 sId = ((ConstraintTag*) tags.first())->_scaleId;
        bool hasSId = ((ConstraintTag*) tags.first())->_hasScaleId;


        foreach (Tag* t, tags) {
            ConstraintTag* ct = (ConstraintTag*) t;
            if (ct->_positionMode != pMode) pModeDifference = true;
            if (ct->_affectX != affectX) affectXDifference = true;
            if (ct->_affectY != affectY) affectYDifference = true;
            if ((ct->_hasPosId != hasPId)
                    || (ct->_hasPosId && hasPId && ct->_posId != pId)) pIdDifference = true;
            if (ct->_rotationMode != rMode) rModeDifference = true;
            if ((ct->_hasRotId != hasRId)
                    || (ct->_hasRotId && hasRId && ct->_rotId != rId)) rIdDifference = true;
            if (ct->_scalationMode != sMode) sModeDifference = true;
            if ((ct->_hasScaleId != hasSId)
                    || (ct->_hasScaleId && hasSId && ct->_scaleId != sId)) sIdDifference = true;
        }

        if (pModeDifference) posComboBox->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else posComboBox->setStyleSheet("");
        if (affectXDifference) affectXCB->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else affectXCB->setStyleSheet("");
        if (affectYDifference) affectYCB->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else affectYCB->setStyleSheet("");
        if (pIdDifference) posObject->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else posObject->setStyleSheet("");
        posComboBox->setCurrentIndex(modeToIndex(pMode));
        affectXCB->setChecked(affectX);
        affectXCB->setEnabled(pMode != Mode::ignore);
        affectYCB->setChecked(affectY);
        affectYCB->setEnabled(pMode != Mode::ignore);
        posObject->setEnabled(pMode != Mode::ignore);
        if (hasPId)
            posObject->setId(pId);
        else
            posObject->clear();

        if (rModeDifference) rotComboBox->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else rotComboBox->setStyleSheet("");
        if (rIdDifference) rotObject->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else rotObject->setStyleSheet("");
        rotComboBox->setCurrentIndex(modeToIndex(rMode));
        rotObject->setEnabled(rMode != Mode::ignore);
        if (hasRId)
            rotObject->setId(rId);
        else
            rotObject->clear();
        if (sModeDifference) scaleComboBox->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else scaleComboBox->setStyleSheet("");
        if (sIdDifference) scaleObject->setStyleSheet(QString("background-color:%1").arg(Property::MULTIPLE_VALUES_COLOR));
        else scaleObject->setStyleSheet("");

        scaleComboBox->setCurrentIndex(modeToIndex(sMode));
        scaleObject->setEnabled(sMode != Mode::ignore);
        if (hasSId)
            scaleObject->setId(sId);
        else
            scaleObject->clear();

        posComboBox->blockSignals(false);
        posObject->blockSignals(false);
        affectXCB->blockSignals(false);
        affectYCB->blockSignals(false);
        rotComboBox->blockSignals(false);
        rotObject->blockSignals(false);
        scaleComboBox->blockSignals(false);
        scaleObject->blockSignals(false);
    };
Example #11
0
static QList<QWidget*> getFormWidgets(QList<FormField> formFields, const QObject *receiver)
{
    QList<QWidget*> formWidgets;

    for (int i = 0; i < formFields.size(); ++i)
    {
        Poppler::FormField *formField = formFields.at(i).field;
        if (formField->type() == Poppler::FormField::FormText)
        {
            Poppler::FormFieldText *formFieldText = static_cast<Poppler::FormFieldText*>(formField);
            switch (formFieldText->textType())
            {
            case Poppler::FormFieldText::FileSelect:
            {
                // TODO replace this by a file selection widget
                QLineEdit *lineEdit = new QLineEdit;
                lineEdit->setText(formFieldText->text());
                lineEdit->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(lineEdit, SIGNAL(textEdited(QString)), receiver, SLOT(slotSetFormData(QString)));
                formWidgets << lineEdit;
            }
            break;
            case Poppler::FormFieldText::Multiline:
            {
                QTextEdit *textEdit = new QTextEdit;
                textEdit->setText(formFieldText->text());
                textEdit->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(textEdit, SIGNAL(textChanged()), receiver, SLOT(slotSetFormData()));
                formWidgets << textEdit;
            }
            break;
            case Poppler::FormFieldText::Normal:
            default:
            {
                QLineEdit *lineEdit = new QLineEdit;
                lineEdit->setText(formFieldText->text());
                lineEdit->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(lineEdit, SIGNAL(textEdited(QString)), receiver, SLOT(slotSetFormData(QString)));
                formWidgets << lineEdit;
            }
            break;
            }
        }
        else if (formField->type() == Poppler::FormField::FormButton)
        {
            Poppler::FormFieldButton *formFieldButton = static_cast<Poppler::FormFieldButton*>(formField);
            switch (formFieldButton->buttonType())
            {
            case Poppler::FormFieldButton::CheckBox:
            {
                QCheckBox *checkBox = new QCheckBox;
//						checkBox->setText(formFieldButton->caption());
                checkBox->setChecked(formFieldButton->state());
                checkBox->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(checkBox, SIGNAL(toggled(bool)), receiver, SLOT(slotSetFormData(bool)));
                formWidgets << checkBox;
            }
            break;
            case Poppler::FormFieldButton::Radio:
            {
                QRadioButton *radioButton = new QRadioButton;
                radioButton->setText(formFieldButton->caption());
                radioButton->setChecked(formFieldButton->state());
                radioButton->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(radioButton, SIGNAL(toggled(bool)), receiver, SLOT(slotSetFormData(bool)));
                formWidgets << radioButton;
            }
            break;
            case Poppler::FormFieldButton::Push:
            default:
            {
                QPushButton *pushButton = new QPushButton;
                pushButton->setText(formFieldButton->caption());
                pushButton->setChecked(formFieldButton->state());
                pushButton->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(pushButton, SIGNAL(toggled(bool)), receiver, SLOT(slotSetFormData(bool)));
                formWidgets << pushButton;
            }
            break;
            }
        }
        else if (formField->type() == Poppler::FormField::FormChoice)
        {
            Poppler::FormFieldChoice *formFieldChoice = static_cast<Poppler::FormFieldChoice*>(formField);
            switch (formFieldChoice->choiceType())
            {
            case Poppler::FormFieldChoice::ComboBox:
            {
                QComboBox *comboBox = new QComboBox;
                comboBox->addItems(formFieldChoice->choices());
                comboBox->setEditable(formFieldChoice->isEditable());
                comboBox->setCurrentIndex(formFieldChoice->currentChoices().at(0));
                comboBox->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(comboBox, SIGNAL(currentIndexChanged(int)), receiver, SLOT(slotSetFormData(int)));
                formWidgets << comboBox;
            }
            break;
            case Poppler::FormFieldChoice::ListBox:
            default:
            {
                QListWidget *listWidget = new QListWidget;
                listWidget->addItems(formFieldChoice->choices());
                if (formFieldChoice->isEditable())
                {
                    for (int j = 0; j < listWidget->count(); ++j)
                        listWidget->item(j)->setFlags(listWidget->item(j)->flags() | Qt::ItemIsEditable);
                }
                else
                {
                    for (int j = 0; j < listWidget->count(); ++j)
                        listWidget->item(j)->setFlags(listWidget->item(j)->flags() & ~Qt::ItemIsEditable);
                }
                QList<int> currentChoices = formFieldChoice->currentChoices();
                for (int j = 0; j < currentChoices.size(); ++j)
                    listWidget->item(currentChoices.at(j))->setSelected(true);
                listWidget->setObjectName(QLatin1String("PageItem::formField") + QString::number(i));
                QObject::connect(listWidget, SIGNAL(itemSelectionChanged()), receiver, SLOT(slotSetFormData()));
                formWidgets << listWidget;
            }
            break;
            }
        }
        else if (formField->type() == Poppler::FormField::FormSignature)
        {
            // TODO
            formWidgets << new QWidget;
        }
        else // make sure that m_formWidgets.at(i) corresponds to m_formFields.at(i)
            formWidgets << new QWidget;
    }

    return formWidgets;
}
void TransactionActionDialog::setData(const QVector<TransactionTable::Data> &data)
{
    for(const TransactionTable::Data& item: data)
    {
        // Add new transaction
        int currRow = ui->tableWidget->rowCount();

        // Insert row after current row
        ui->tableWidget->insertRow(currRow);

        // Create new plus minus widget
        PlusMinusPushWidget* plusMinusWidget = new PlusMinusPushWidget(
                    ui->tableWidget);

        // Create temporary variable to hold the item amount.
        // This is due to the const restrictions, we can not modify the value
        // directly
        int tempNoStock = item.noSold;

        // Check if value is negative
        if(tempNoStock < 0)
        {
            // Click the button so that its set to -
            plusMinusWidget->click();
            // Make value positive
            tempNoStock *= -1;
        }


        // Set the plus minus widget to the table
        ui->tableWidget->setCellWidget(currRow, POS_NEG, plusMinusWidget);

        // Create combo box that links to stock table model
        // and add to row and column
        QComboBox* comboBox = new QComboBox(ui->tableWidget);
        comboBox->setModel(m_stockTable);
        // show the reference column
        comboBox->setModelColumn(StockTable::REF);

        // get view index from model
        int stock_index = DB::GetViewIndex(item.stock_id,
                         static_cast<QSqlQueryModel*>(m_stockTable));

        // Set index of row to view index we found earlier
        comboBox->setCurrentIndex(stock_index);
        // Set widget to table
        ui->tableWidget->setCellWidget(currRow, STOCK_ITEM, comboBox);

        // create new line edit containing amount data
        QLineEdit* lineEdit = new QLineEdit(QString::number(item.amount, 'd', 2), ui->tableWidget);
        // set numeric values only regex
        lineEdit->setValidator(DB::GetNumericValidator(lineEdit));

        // set line edit in to amount column
        ui->tableWidget->setCellWidget(currRow, AMOUNT,
                   lineEdit);

        // create new line edit containing number of stock data
        lineEdit = new QLineEdit(QString::number(tempNoStock), ui->tableWidget);
        // set validator as non negative regex
        lineEdit->setValidator(DB::GetNonNegativeNumericValidator(lineEdit));

        // set the line edit widget in to the no sold column
        ui->tableWidget->setCellWidget(currRow, NO_SOLD, lineEdit);

        // create line edit, add id number and insert in to id column
        ui->tableWidget->setCellWidget(currRow, ID,
                   new QLineEdit(QString::number(item.id), ui->tableWidget));

        // create line edit, add deleted mark and insert in to deleted column
        ui->tableWidget->setCellWidget(currRow, DELETED,
                   new QLineEdit(QString::number(item.deleted, 'd', 2), ui->tableWidget));
    }
}
Example #13
0
Channels::Channels(QWidget * parent, ModelData & model, GeneralSettings & generalSettings, FirmwareInterface * firmware):
  ModelPanel(parent, model, generalSettings, firmware)
{
  QGridLayout * gridLayout = new QGridLayout(this);
  bool minimize = false;

  int col = 1;
  if (firmware->getCapability(ChannelsName))
  {
    minimize=true;
    addLabel(gridLayout, tr("Name"), col++);
  }
  addLabel(gridLayout, tr("Subtrim"), col++, minimize);
  addLabel(gridLayout, tr("Min"), col++, minimize);
  addLabel(gridLayout, tr("Max"), col++, minimize);
  addLabel(gridLayout, tr("Direction"), col++, minimize);
  if (IS_TARANIS(GetEepromInterface()->getBoard()))
    addLabel(gridLayout, tr("Curve"), col++, minimize);
  if (firmware->getCapability(PPMCenter))
    addLabel(gridLayout, tr("PPM Center"), col++, minimize);
  if (firmware->getCapability(SYMLimits))
    addLabel(gridLayout, tr("Linear Subtrim"), col++, true);

  for (int i=0; i<firmware->getCapability(Outputs); i++) {
    col = 0;

    // Channel label
    QLabel *label = new QLabel(this);
    label->setText(tr("Channel %1").arg(i+1));
    label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
    gridLayout->addWidget(label, i+1, col++, 1, 1);

    // Channel name
    int nameLen = firmware->getCapability(ChannelsName);
    if (nameLen > 0) {
      QLineEdit * name = new QLineEdit(this);
      name->setProperty("index", i);
      name->setMaxLength(nameLen);
      QRegExp rx(CHAR_FOR_NAMES_REGEX);
      name->setValidator(new QRegExpValidator(rx, this));
      name->setText(model.limitData[i].name);
      connect(name, SIGNAL(editingFinished()), this, SLOT(nameEdited()));
      gridLayout->addWidget(name, i+1, col++, 1, 1);
    }

    // Channel offset
    QDoubleSpinBox * offset = new QDoubleSpinBox(this);
    offset->setProperty("index", i);
    offset->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
    offset->setAccelerated(true);
    offset->setDecimals(1);
    offset->setMinimum(-100);
    offset->setSingleStep(0.1);
    offset->setValue(float(model.limitData[i].offset) / 10);
    connect(offset, SIGNAL(editingFinished()), this, SLOT(offsetEdited()));
    gridLayout->addWidget(offset, i+1, col++, 1, 1);

    // Channel min
    QDoubleSpinBox * minSB = new QDoubleSpinBox(this);
    minSB->setProperty("index", i);
    minSB->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
    minSB->setAccelerated(true);
    minSB->setDecimals(1);
    minSB->setMinimum(-model.getChannelsMax());
    minSB->setSingleStep(0.1);
    minSB->setMaximum(0);
    minSB->setValue(float(model.limitData[i].min) / 10);
    connect(minSB, SIGNAL(editingFinished()), this, SLOT(minEdited()));
    gridLayout->addWidget(minSB, i+1, col++, 1, 1);
    minSpins << minSB;

    // Channel max
    QDoubleSpinBox * maxSB = new QDoubleSpinBox(this);
    maxSB->setProperty("index", i);
    maxSB->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
    maxSB->setAccelerated(true);
    maxSB->setDecimals(1);
    maxSB->setMinimum(0);
    maxSB->setSingleStep(0.1);
    maxSB->setMaximum(model.getChannelsMax());
    maxSB->setValue(float(model.limitData[i].max) / 10);
    connect(maxSB, SIGNAL(editingFinished()), this, SLOT(maxEdited()));
    gridLayout->addWidget(maxSB, i+1, col++, 1, 1);
    maxSpins << maxSB;

    // Channel inversion
    QComboBox * invCB = new QComboBox(this);
    invCB->insertItems(0, QStringList() << tr("---") << tr("INV"));
    invCB->setProperty("index", i);
    invCB->setCurrentIndex((model.limitData[i].revert) ? 1 : 0);
    connect(invCB, SIGNAL(currentIndexChanged(int)), this, SLOT(invEdited()));
    gridLayout->addWidget(invCB, i+1, col++, 1, 1);

    // Curve
    if (IS_TARANIS(GetEepromInterface()->getBoard())) {
      QComboBox * curveCB = new QComboBox(this);
      curveCB->setProperty("index", i);
      int numcurves = firmware->getCapability(NumCurves);
      for (int j=-numcurves; j<=numcurves; j++) {
        curveCB->addItem(CurveReference(CurveReference::CURVE_REF_CUSTOM, j).toString(), j);
      }
      curveCB->setCurrentIndex(model.limitData[i].curve.value+numcurves);
      connect(curveCB, SIGNAL(currentIndexChanged(int)), this, SLOT(curveEdited()));
      gridLayout->addWidget(curveCB, i+1, col++, 1, 1);
    }

    // PPM center
    if (firmware->getCapability(PPMCenter)) {
      QSpinBox * center = new QSpinBox(this);
      center->setProperty("index", i);
      center->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
      center->setMinimum(1375);
      center->setMaximum(1625);
      center->setValue(1500);
      center->setValue(model.limitData[i].ppmCenter + 1500);
      connect(center, SIGNAL(editingFinished()), this, SLOT(ppmcenterEdited()));
      gridLayout->addWidget(center, i+1, col++, 1, 1);
    }

    // Symetrical limits
    if (firmware->getCapability(SYMLimits)) {
      QCheckBox * symlimits = new QCheckBox(this);
      symlimits->setProperty("index", i);
      symlimits->setChecked(model.limitData[i].symetrical);
      connect(symlimits, SIGNAL(toggled(bool)), this, SLOT(symlimitsEdited()));
      gridLayout->addWidget(symlimits, i+1, col++, 1, 1);
    }
  }
Example #14
0
void protoObject::propertyUpdated(QString propertyName){
    QObject *receiver = mapper->mapping(propertyName);
    QWidget *widget;

    if (receiver) return; //if not binding, just leave

    widget = qobject_cast<QLabel*>(receiver);
    if (widget) {
        QLabel* edit = qobject_cast<QLabel*>(receiver);
        QString value = this->property(propertyName.toLatin1()).toString();
        edit->blockSignals(true);
        edit->setText(edit->text().arg(value));
        edit->blockSignals(false);
    };

    widget = qobject_cast<QLineEdit*>(receiver);
    if (widget) {
        QLineEdit* edit = qobject_cast<QLineEdit*>(receiver);
        QString value = this->property(propertyName.toLatin1()).toString();
        edit->blockSignals(true);
        edit->setText(value);
        edit->blockSignals(false);
    };

    widget = qobject_cast<QComboBox*>(receiver);
    if (widget) {
        QComboBox* edit = qobject_cast<QComboBox*>(receiver);
        edit->blockSignals(true);
        edit->setCurrentIndex(edit->findData(this->property(propertyName.toLatin1()), Qt::UserRole));
        edit->blockSignals(false);
    };

    widget = qobject_cast<QRadioButton*>(receiver);
    if (widget) {
        QRadioButton* edit = qobject_cast<QRadioButton*>(receiver);
        bool value = this->property(propertyName.toLatin1()).toBool();
        edit->blockSignals(true);
        edit->setChecked(value);
        edit->blockSignals(false);
    };

    widget = qobject_cast<QCheckBox*>(receiver);
    if (widget) {
        QCheckBox* edit = qobject_cast<QCheckBox*>(receiver);
        bool value = this->property(propertyName.toLatin1()).toBool();
        edit->blockSignals(true);
        edit->setChecked(value);
        edit->blockSignals(false);
    };

    widget = qobject_cast<QPlainTextEdit*>(receiver);
    if (widget) {
        QPlainTextEdit* edit = qobject_cast<QPlainTextEdit*>(receiver);
        QString value = this->property(propertyName.toLatin1()).toString();
        edit->blockSignals(true);
        edit->setPlainText(value);
        edit->blockSignals(false);
    };

    widget = qobject_cast<QSpinBox*>(receiver);
    if (widget) {
        QSpinBox* edit = qobject_cast<QSpinBox*>(receiver);
        int value = this->property(propertyName.toLatin1()).toInt();
        edit->blockSignals(true);
        edit->setValue(value);
        edit->blockSignals(false);
    };

    widget = qobject_cast<QDoubleSpinBox*>(receiver);
    if (widget) {
        QDoubleSpinBox* edit = qobject_cast<QDoubleSpinBox*>(receiver);
        double value = this->property(propertyName.toLatin1()).toDouble();
        edit->blockSignals(true);
        edit->setValue(value);
        edit->blockSignals(false);
    };

    widget = qobject_cast<QDateTimeEdit*>(receiver);
    if (widget) {
        QDateTimeEdit* edit = qobject_cast<QDateTimeEdit*>(receiver);
        QDateTime value = this->property(propertyName.toLatin1()).toDateTime();
        edit->blockSignals(true);
        edit->setDateTime(value);
        edit->blockSignals(false);
    };
}
void DesignerFields::load( DesignerFields::Storage *storage )
{
  QStringList keys = storage->keys();

  // clear all custom page widgets
  // we can't do this in the following loop, as it works on the
  // custom fields of the vcard, which may not be set.
  QMap<QString, QWidget *>::ConstIterator widIt;
  for ( widIt = mWidgets.constBegin(); widIt != mWidgets.constEnd(); ++widIt ) {
    QString value;
    if ( widIt.value()->inherits( "QLineEdit" ) ) {
      QLineEdit *wdg = static_cast<QLineEdit*>( widIt.value() );
      wdg->setText( QString() );
    } else if ( widIt.value()->inherits( "QSpinBox" ) ) {
      QSpinBox *wdg = static_cast<QSpinBox*>( widIt.value() );
      wdg->setValue( wdg->minimum() );
    } else if ( widIt.value()->inherits( "QCheckBox" ) ) {
      QCheckBox *wdg = static_cast<QCheckBox*>( widIt.value() );
      wdg->setChecked( false );
    } else if ( widIt.value()->inherits( "QDateTimeEdit" ) ) {
      Q3DateTimeEdit *wdg = static_cast<Q3DateTimeEdit*>( widIt.value() );
      wdg->setDateTime( QDateTime::currentDateTime() );
    } else if ( widIt.value()->inherits( "KDateTimeWidget" ) ) {
      KDateTimeWidget *wdg = static_cast<KDateTimeWidget*>( widIt.value() );
      wdg->setDateTime( QDateTime::currentDateTime() );
    } else if ( widIt.value()->inherits( "KDatePicker" ) ) {
      KDatePicker *wdg = static_cast<KDatePicker*>( widIt.value() );
      wdg->setDate( QDate::currentDate() );
    } else if ( widIt.value()->inherits( "QComboBox" ) ) {
      QComboBox *wdg = static_cast<QComboBox*>( widIt.value() );
      wdg->setCurrentIndex( 0 );
    } else if ( widIt.value()->inherits( "QTextEdit" ) ) {
      QTextEdit *wdg = static_cast<QTextEdit*>( widIt.value() );
      wdg->setPlainText( QString() );
    }
  }

  QStringList::ConstIterator it2;
  for ( it2 = keys.constBegin(); it2 != keys.constEnd(); ++it2 ) {
    QString value = storage->read( *it2 );

    QMap<QString, QWidget *>::ConstIterator it = mWidgets.constFind( *it2 );
    if ( it != mWidgets.constEnd() ) {
      if ( it.value()->inherits( "QLineEdit" ) ) {
        QLineEdit *wdg = static_cast<QLineEdit*>( it.value() );
        wdg->setText( value );
      } else if ( it.value()->inherits( "QSpinBox" ) ) {
        QSpinBox *wdg = static_cast<QSpinBox*>( it.value() );
        wdg->setValue( value.toInt() );
      } else if ( it.value()->inherits( "QCheckBox" ) ) {
        QCheckBox *wdg = static_cast<QCheckBox*>( it.value() );
        wdg->setChecked( value == "true" || value == "1" );
      } else if ( it.value()->inherits( "QDateTimeEdit" ) ) {
        Q3DateTimeEdit *wdg = static_cast<Q3DateTimeEdit*>( it.value() );
        wdg->setDateTime( QDateTime::fromString( value, Qt::ISODate ) );
      } else if ( it.value()->inherits( "KDateTimeWidget" ) ) {
        KDateTimeWidget *wdg = static_cast<KDateTimeWidget*>( it.value() );
        wdg->setDateTime( QDateTime::fromString( value, Qt::ISODate ) );
      } else if ( it.value()->inherits( "KDatePicker" ) ) {
        KDatePicker *wdg = static_cast<KDatePicker*>( it.value() );
        wdg->setDate( QDate::fromString( value, Qt::ISODate ) );
      } else if ( it.value()->inherits( "QComboBox" ) ) {
        QComboBox *wdg = static_cast<QComboBox*>( it.value() );
        wdg->setItemText( wdg->currentIndex(), value );
      } else if ( it.value()->inherits( "QTextEdit" ) ) {
        QTextEdit *wdg = static_cast<QTextEdit*>( it.value() );
        wdg->setPlainText( value );
      }
    }
  }
}
Example #16
0
void AdjustSubnets::show()
{
    QDialog::show();
    scenarioName->setText(QString(     "Scenario Name:       ") + extractor->setup->scenarioName->text());
    scenarioDirectory->setText(QString("Scenario Directory:  ") + extractor->setup->scenarioDirectory->text());

    tableWidget->horizontalHeaderItem(0)->setToolTip("This is the name of the radio. It consists of the EXata/QualNet name and the interface id");
    tableWidget->horizontalHeaderItem(1)->setToolTip("The radio belongs to this force");
    tableWidget->horizontalHeaderItem(2)->setToolTip("Select an IPv4 subnet for the radio to use for communicationsI");

    QStringList addrs;
    SNT_HLA::NetworkSet& nets = extractor->ns->networksUsed();
    SNT_HLA::NetworkSet::iterator netIt = nets.begin();
    while( netIt != nets.end() )
    {
        QString addr((*netIt)->address.c_str());
        if( addrs.indexOf(addr) == -1 )
            addrs << addr;
        netIt++;
    }

    tableWidget->clearContents();
    tableWidget->setRowCount(0);
    QAbstractItemModel* model = tableWidget->model();
    rowInfo.clear();
    SNT_HLA::NodeSet::iterator it = extractor->ns->begin();
    while( it != extractor->ns->end() )
    {
        QApplication::processEvents();
        if( extractor == 0 )
            break;
        if( (*it)->entity )
        {
            std::set<SNT_HLA::RadioTransmitter*>::iterator rit = (*it)->radios.begin();
            while( rit != (*it)->radios.end() )
            {
                int row = tableWidget->rowCount();
                tableWidget->insertRow(row);

                subnetRowInfo info;
                info.row = row;
                info.node = *it;
                info.net = extractor->ns->getNetwork(*it, (*rit));
                rowInfo.append(info);

                QString name = QString((*it)->getNodeName()) + ":" + QString::number((*rit)->RadioIndex);
                QString addr(extractor->ns->getNetworkAddress(*it, (*rit)).c_str());
                QModelIndex index = model->index(row, 0, QModelIndex());
                std::stringstream fs;
                fs << (*it)->entity->ForceIdentifier << std::ends;
                QString force = fs.str().c_str();
                model->setData(index, name);
                index = model->index(row, 1, QModelIndex());
                model->setData(index, force);
                QComboBox* box = new QComboBox;
                box->addItems(addrs);
                int idx = addrs.indexOf(addr);
                if( idx == -1 )
                {
                    idx = box->count();
                    box->insertItem(idx, addr);
                }
                box->setCurrentIndex(idx);
                box->setToolTip("Select an IPv4 subnet for the radio to use for communications");
                tableWidget->setCellWidget(row, 2, box);
                tableWidget->item(row, 0)->setFlags(0);
                tableWidget->item(row, 1)->setFlags(0);
                tableWidget->item(row,0)->setToolTip("This is the name of the radio. It consists of the EXata/QualNet name and the interface id");
                tableWidget->item(row,1)->setToolTip("The radio belongs to this force");
                tableWidget->resizeColumnToContents(0);
                rit++;
            }
        }
        it++;
    }
}
Example #17
0
//==========================
void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
  int value = index.model()->data(index, Qt::DisplayRole).toInt();
  QComboBox *combo = static_cast<QComboBox*>(editor);
  combo->setCurrentIndex(value);
}
Example #18
0
int main(int argc, char **argv)
{
    //! [0]
    QApplication app(argc, argv);
    Q3DSurface *graph = new Q3DSurface();
    QWidget *container = QWidget::createWindowContainer(graph);
    //! [0]

    if (!graph->hasContext()) {
        QMessageBox msgBox;
        msgBox.setText("Couldn't initialize the OpenGL context.");
        msgBox.exec();
        return -1;
    }

    QSize screenSize = graph->screen()->size();
    container->setMinimumSize(QSize(screenSize.width() / 2, screenSize.height() / 1.6));
    container->setMaximumSize(screenSize);
    container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    container->setFocusPolicy(Qt::StrongFocus);

    //! [1]
    QWidget *widget = new QWidget;
    QHBoxLayout *hLayout = new QHBoxLayout(widget);
    QVBoxLayout *vLayout = new QVBoxLayout();
    hLayout->addWidget(container, 1);
    hLayout->addLayout(vLayout);
    vLayout->setAlignment(Qt::AlignTop);
    //! [1]

    widget->setWindowTitle(QStringLiteral("Surface example"));

    QGroupBox *modelGroupBox = new QGroupBox(QStringLiteral("Model"));

    QRadioButton *sqrtSinModelRB = new QRadioButton(widget);
    sqrtSinModelRB->setText(QStringLiteral("Sqrt && Sin"));
    sqrtSinModelRB->setChecked(false);

    QRadioButton *heightMapModelRB = new QRadioButton(widget);
    heightMapModelRB->setText(QStringLiteral("Height Map"));
    heightMapModelRB->setChecked(false);

    QVBoxLayout *modelVBox = new QVBoxLayout;
    modelVBox->addWidget(sqrtSinModelRB);
    modelVBox->addWidget(heightMapModelRB);
    modelGroupBox->setLayout(modelVBox);

    QGroupBox *selectionGroupBox = new QGroupBox(QStringLiteral("Selection Mode"));

    QRadioButton *modeNoneRB = new QRadioButton(widget);
    modeNoneRB->setText(QStringLiteral("No selection"));
    modeNoneRB->setChecked(false);

    QRadioButton *modeItemRB = new QRadioButton(widget);
    modeItemRB->setText(QStringLiteral("Item"));
    modeItemRB->setChecked(false);

    QRadioButton *modeSliceRowRB = new QRadioButton(widget);
    modeSliceRowRB->setText(QStringLiteral("Row Slice"));
    modeSliceRowRB->setChecked(false);

    QRadioButton *modeSliceColumnRB = new QRadioButton(widget);
    modeSliceColumnRB->setText(QStringLiteral("Column Slice"));
    modeSliceColumnRB->setChecked(false);

    QVBoxLayout *selectionVBox = new QVBoxLayout;
    selectionVBox->addWidget(modeNoneRB);
    selectionVBox->addWidget(modeItemRB);
    selectionVBox->addWidget(modeSliceRowRB);
    selectionVBox->addWidget(modeSliceColumnRB);
    selectionGroupBox->setLayout(selectionVBox);

    QSlider *axisMinSliderX = new QSlider(Qt::Horizontal, widget);
    axisMinSliderX->setMinimum(0);
    axisMinSliderX->setTickInterval(1);
    axisMinSliderX->setEnabled(true);
    QSlider *axisMaxSliderX = new QSlider(Qt::Horizontal, widget);
    axisMaxSliderX->setMinimum(1);
    axisMaxSliderX->setTickInterval(1);
    axisMaxSliderX->setEnabled(true);
    QSlider *axisMinSliderZ = new QSlider(Qt::Horizontal, widget);
    axisMinSliderZ->setMinimum(0);
    axisMinSliderZ->setTickInterval(1);
    axisMinSliderZ->setEnabled(true);
    QSlider *axisMaxSliderZ = new QSlider(Qt::Horizontal, widget);
    axisMaxSliderZ->setMinimum(1);
    axisMaxSliderZ->setTickInterval(1);
    axisMaxSliderZ->setEnabled(true);

    QComboBox *themeList = new QComboBox(widget);
    themeList->addItem(QStringLiteral("Qt"));
    themeList->addItem(QStringLiteral("Primary Colors"));
    themeList->addItem(QStringLiteral("Digia"));
    themeList->addItem(QStringLiteral("Stone Moss"));
    themeList->addItem(QStringLiteral("Army Blue"));
    themeList->addItem(QStringLiteral("Retro"));
    themeList->addItem(QStringLiteral("Ebony"));
    themeList->addItem(QStringLiteral("Isabelle"));

    QGroupBox *colorGroupBox = new QGroupBox(QStringLiteral("Custom gradient"));

    QLinearGradient grBtoY(0, 0, 1, 100);
    grBtoY.setColorAt(1.0, Qt::black);
    grBtoY.setColorAt(0.67, Qt::blue);
    grBtoY.setColorAt(0.33, Qt::red);
    grBtoY.setColorAt(0.0, Qt::yellow);
    QPixmap pm(24, 100);
    QPainter pmp(&pm);
    pmp.setBrush(QBrush(grBtoY));
    pmp.setPen(Qt::NoPen);
    pmp.drawRect(0, 0, 24, 100);
    QPushButton *gradientBtoYPB = new QPushButton(widget);
    gradientBtoYPB->setIcon(QIcon(pm));
    gradientBtoYPB->setIconSize(QSize(24, 100));

    QLinearGradient grGtoR(0, 0, 1, 100);
    grGtoR.setColorAt(1.0, Qt::darkGreen);
    grGtoR.setColorAt(0.5, Qt::yellow);
    grGtoR.setColorAt(0.2, Qt::red);
    grGtoR.setColorAt(0.0, Qt::darkRed);
    pmp.setBrush(QBrush(grGtoR));
    pmp.drawRect(0, 0, 24, 100);
    QPushButton *gradientGtoRPB = new QPushButton(widget);
    gradientGtoRPB->setIcon(QIcon(pm));
    gradientGtoRPB->setIconSize(QSize(24, 100));

    QHBoxLayout *colorHBox = new QHBoxLayout;
    colorHBox->addWidget(gradientBtoYPB);
    colorHBox->addWidget(gradientGtoRPB);
    colorGroupBox->setLayout(colorHBox);

    vLayout->addWidget(modelGroupBox);
    vLayout->addWidget(selectionGroupBox);
    vLayout->addWidget(new QLabel(QStringLiteral("Column range")));
    vLayout->addWidget(axisMinSliderX);
    vLayout->addWidget(axisMaxSliderX);
    vLayout->addWidget(new QLabel(QStringLiteral("Row range")));
    vLayout->addWidget(axisMinSliderZ);
    vLayout->addWidget(axisMaxSliderZ);
    vLayout->addWidget(new QLabel(QStringLiteral("Theme")));
    vLayout->addWidget(themeList);
    vLayout->addWidget(colorGroupBox);

    widget->show();

    SurfaceGraph *modifier = new SurfaceGraph(graph);

    QObject::connect(heightMapModelRB, &QRadioButton::toggled,
                     modifier, &SurfaceGraph::enableHeightMapModel);
    QObject::connect(sqrtSinModelRB, &QRadioButton::toggled,
                     modifier, &SurfaceGraph::enableSqrtSinModel);
    QObject::connect(modeNoneRB, &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeNone);
    QObject::connect(modeItemRB,  &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeItem);
    QObject::connect(modeSliceRowRB,  &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeSliceRow);
    QObject::connect(modeSliceColumnRB,  &QRadioButton::toggled,
                     modifier, &SurfaceGraph::toggleModeSliceColumn);
    QObject::connect(axisMinSliderX, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustXMin);
    QObject::connect(axisMaxSliderX, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustXMax);
    QObject::connect(axisMinSliderZ, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustZMin);
    QObject::connect(axisMaxSliderZ, &QSlider::valueChanged,
                     modifier, &SurfaceGraph::adjustZMax);
    QObject::connect(themeList, SIGNAL(currentIndexChanged(int)),
                     modifier, SLOT(changeTheme(int)));
    QObject::connect(gradientBtoYPB, &QPushButton::pressed,
                     modifier, &SurfaceGraph::setBlackToYellowGradient);
    QObject::connect(gradientGtoRPB, &QPushButton::pressed,
                     modifier, &SurfaceGraph::setGreenToRedGradient);

    modifier->setAxisMinSliderX(axisMinSliderX);
    modifier->setAxisMaxSliderX(axisMaxSliderX);
    modifier->setAxisMinSliderZ(axisMinSliderZ);
    modifier->setAxisMaxSliderZ(axisMaxSliderZ);

    sqrtSinModelRB->setChecked(true);
    modeItemRB->setChecked(true);
    themeList->setCurrentIndex(2);

    return app.exec();
}
Example #19
0
void AsciiOpenDlg::updateTable()
{
    m_ui->tableWidget->setEnabled(false);
    m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false);

    bool hadValidHeader = !m_headerLine.isEmpty();
    m_headerLine.clear();

    if (m_filename.isEmpty())
    {
        m_ui->tableWidget->clear();
        return;
    }
    //we open the file in ASCII mode
    QFile file(m_filename);
    if (!file.open(QFile::ReadOnly))
    {
        m_ui->tableWidget->clear();
        m_columnsValidty.clear();
        return;
    }
    QTextStream stream(&file);

    //we skip first lines (if needed)
    {
        for (unsigned i=0; i<m_skippedLines; ++i)
        {
            QString currentLine = stream.readLine();
            //we keep track of the first line
            if (i == 0)
                m_headerLine = currentLine;
        }
    }

    //if the old setup has less than 3 columns, we forget it
    if (m_columnsCount < 3)
    {
        m_ui->tableWidget->clear();
        m_columnsCount = 0;
    }
    m_ui->tableWidget->setRowCount(DISPLAYED_LINES+1);    //+1 for first line shifting

    unsigned lineCount = 0;			//number of lines read
    unsigned totalChars = 0;		//total read characters (for stats)
    unsigned columnsCount = 0;		//max columns count per line
    unsigned commentLines = 0;		//number of comments line skipped

    std::vector<bool> valueIsNumber;	//identifies columns with numbers only [mandatory]
    std::vector<bool> valueIsBelowOne;	//identifies columns with values between -1 and 1 only
    std::vector<bool> valueIsInteger;	//identifies columns with integer values only
    std::vector<bool> valueIsBelow255;	//identifies columns with integer values between 0 and 255 only

    QChar decimalPoint = QLocale().decimalPoint();
    QString currentLine = stream.readLine();
    while (lineCount < LINES_READ_FOR_STATS && !currentLine.isNull())
    {
        //we recognize "//" as the beginning of a comment
        if (!currentLine.startsWith("//"))
        {
            QStringList parts = currentLine.trimmed().split(m_separator,QString::SkipEmptyParts);
            if (lineCount < DISPLAYED_LINES)
            {
                unsigned partsCount = std::min( MAX_COLUMNS, static_cast<unsigned>(parts.size()) );

                //do we need to add one or several new columns?
                if (partsCount > columnsCount)
                {
                    //we also extend vectors
                    for (unsigned i = columnsCount; i < partsCount; ++i)
                    {
                        valueIsNumber.push_back(true);
                        valueIsBelowOne.push_back(true);
                        valueIsBelow255.push_back(true);
                        valueIsInteger.push_back(true);
                    }

                    m_ui->tableWidget->setColumnCount(partsCount);
                    columnsCount = partsCount;
                }

                //we fill the current row with extracted parts
                for (unsigned i = 0; i < partsCount; ++i)
                {
                    QTableWidgetItem *newItem = new QTableWidgetItem(parts[i]);

                    //test values
                    bool isANumber = false;
                    double value = parts[i].toDouble(&isANumber);
                    if (!isANumber)
                    {
                        valueIsNumber[i] = false;
                        valueIsBelowOne[i] = false;
                        valueIsInteger[i] = false;
                        valueIsBelow255[i] = false;
                        newItem->setBackground(QBrush(QColor(255, 160, 160)));
                    }
                    else
                    {
                        valueIsBelowOne[i] = valueIsBelowOne[i] && (fabs(value) <= 1.0);
                        valueIsInteger[i] = valueIsInteger[i] && !parts[i].contains(decimalPoint);
                        valueIsBelow255[i] = valueIsBelow255[i] && valueIsInteger[i] && (value >= 0.0 && value <= 255.0);
                    }

                    m_ui->tableWidget->setItem(lineCount + 1, i, newItem); //+1 for first line shifting
                }
            }

            totalChars += currentLine.size() + 1; //+1 for return char at eol
            ++lineCount;
        }
        else
        {
            if (m_skippedLines == 0 && commentLines == 0)
            {
                //if the very first line is a comment, then we force the user to skip it!
                //this way it will be considered as a header
                m_ui->spinBoxSkipLines->setMinimum(1);
                return;
            }
            ++commentLines;
        }

        //read next line
        currentLine = stream.readLine();
    }

    file.close();

    //process header line
    if (!m_headerLine.isEmpty())
    {
        m_headerLine = m_headerLine.trimmed();
        int n = 0;
        while (n < m_headerLine.size() && m_headerLine.at(n) == '/')
            ++n;
        if (n != 0)
            m_headerLine.remove(0,n);
        m_ui->headerLabel->setText(QString("Header: ")+m_headerLine);
        m_ui->headerLabel->setVisible(true);
    }
    else
    {
        m_ui->headerLabel->setVisible(false);
    }

    m_ui->commentLinesSkippedLabel->setVisible(commentLines != 0);
    if (commentLines)
        m_ui->commentLinesSkippedLabel->setText(QString("+ %1 comment line(s) skipped").arg(commentLines));

    if (lineCount == 0 || columnsCount == 0)
    {
        m_averageLineSize = -1.0;
        m_ui->tableWidget->clear();
        m_columnsValidty.clear();
        return;
    }

    //average line size
    m_averageLineSize = static_cast<double>(totalChars)/lineCount;

    //we add a type selector for each column
    QStringList propsText;
    {
        for (unsigned i=0; i<ASCII_OPEN_DLG_TYPES_NUMBER; i++)
            propsText << QString(ASCII_OPEN_DLG_TYPES_NAMES[i]);
    }

    //remove unnecessary columns
    {
        while (columnsCount < m_columnsCount)
            m_ui->tableWidget->removeColumn(--m_columnsCount);
        if (m_columnsValidty.size() > columnsCount)
            m_columnsValidty.resize(columnsCount);
        for (unsigned i=lineCount+1; i<=DISPLAYED_LINES; ++i)
            m_ui->tableWidget->removeRow(i);
    }

    //setup table and widgets
    {
        //Icons
        static const QIcon xIcon		(QString::fromUtf8(":/CC/images/typeXCoordinate.png"));
        static const QIcon yIcon		(QString::fromUtf8(":/CC/images/typeYCoordinate.png"));
        static const QIcon zIcon		(QString::fromUtf8(":/CC/images/typeZCoordinate.png"));
        static const QIcon NormIcon		(QString::fromUtf8(":/CC/images/typeNormal.png"));
        static const QIcon RGBIcon		(QString::fromUtf8(":/CC/images/typeRgbCcolor.png"));
        static const QIcon GreyIcon		(QString::fromUtf8(":/CC/images/typeGrayColor.png"));
        static const QIcon ScalarIcon	(QString::fromUtf8(":/CC/images/typeSF.png"));

        int columnWidth = (m_ui->tableWidget->width()*9) / (columnsCount*10);
        columnWidth = std::max(columnWidth,80);

        for (unsigned i=0; i<columnsCount; i++)
        {
            QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0,i));
            QComboBox* _columnHeader = columnHeaderWidget;
            if (!columnHeaderWidget)
            {
                columnHeaderWidget = new QComboBox();
                columnHeaderWidget->addItems(propsText);
                columnHeaderWidget->setMaxVisibleItems(ASCII_OPEN_DLG_TYPES_NUMBER);
                columnHeaderWidget->setCurrentIndex(0);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_X,xIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Y,yIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Z,zIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NX,NormIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NY,NormIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NZ,NormIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_R,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_G,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_B,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Rf,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Gf,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Bf,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Grey,GreyIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Scalar,ScalarIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32i,RGBIcon);
                columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32f,RGBIcon);

                connect(columnHeaderWidget, SIGNAL(currentIndexChanged(int)), this, SLOT(columnsTypeHasChanged(int)));
            }

            while (m_columnsValidty.size() <= static_cast<size_t>(i))
                m_columnsValidty.push_back(false);
            assert(m_columnsValidty.size() >= static_cast<size_t>(i));

            if (!_columnHeader)
                m_ui->tableWidget->setCellWidget(0,i,columnHeaderWidget);
            m_ui->tableWidget->setColumnWidth(i,columnWidth);

            //a non-numerical column can't be valid
            if (!valueIsNumber[i])
                m_columnsValidty[i] = false;
        }
    }
Example #20
0
/*!
 * \brief displays specified sensor parameters in the gui.
 * The sepecial gui elements are constructed dynamically.
 */
void StationInfoDialog::getSensorParameters()
{
    if(OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument != NULL && OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getDoubleParameter() != NULL){

        QMap<QString, double> doubleparam = *OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getDoubleParameter();

        QMapIterator<QString, double> j(doubleparam);
        while(j.hasNext()){
            j.next();

            QLabel *l = new QLabel();
            l->setText(j.key());
            QLineEdit *le = new QLineEdit();
            //le->setText(QString::number(j.value()));
            le->setText(QString::number(OiFeatureState::getActiveFeature()->getStation()->getInstrumentConfig()->doubleParameter.value(j.key())));

            QHBoxLayout *layout = new QHBoxLayout();
            layout->addWidget(l);
            layout->addWidget(le);
            layout->setStretch(0,1);
            layout->setStretch(1,1);

            masterSensorConfigLayout->addLayout(layout);

            doubleParameter.insert(j.key(),le);
            doubleParameterLabel.insert(j.key(),l);
            sensorConfigLayouts.insert(j.key(),layout);
        }
    }

    if(OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument != NULL && OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getIntegerParameter() != NULL){

        QMap<QString, int> intParameter = *OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getIntegerParameter();

        QMapIterator<QString, int> k(intParameter);
        while(k.hasNext()){
            k.next();

            QLabel *l = new QLabel();
            l->setText(k.key());
            QLineEdit *le = new QLineEdit();
            //le->setText(QString::number(k.value()));
            le->setText(QString::number(OiFeatureState::getActiveFeature()->getStation()->getInstrumentConfig()->integerParameter.value(k.key())));

            QHBoxLayout *layout = new QHBoxLayout();
            layout->addWidget(l);
            layout->addWidget(le);
            layout->setStretch(0,1);
            layout->setStretch(1,1);

            masterSensorConfigLayout->addLayout(layout);

            integerParameter.insert(k.key(),le);
            integerParameterLabel.insert(k.key(),l);
            sensorConfigLayouts.insert(k.key(),layout);
        }
    }

    if(OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument != NULL && OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getStringParameter() != NULL){

        QMap<QString,QStringList> strParameter = *OiFeatureState::getActiveFeature()->getStation()->sensorPad->instrument->getStringParameter();

        QMapIterator<QString,QStringList> m(strParameter);
        while(m.hasNext()){
            m.next();

            QLabel *l = new QLabel();
            l->setText(m.key());
            QComboBox *cb = new QComboBox();
            for(int a=0;a< m.value().size();a++){
                cb->addItem(m.value().at(a));
            }
            cb->setCurrentIndex(cb->findText(OiFeatureState::getActiveFeature()->getStation()->getInstrumentConfig()->stringParameter.value(m.key())));

            QHBoxLayout *layout = new QHBoxLayout();
            layout->addWidget(l);
            layout->addWidget(cb);
            layout->setStretch(0,1);
            layout->setStretch(1,1);

            masterSensorConfigLayout->addLayout(layout);

            stringParameter.insert(m.key(),cb);
            stringParameterLabel.insert(m.key(),l);
            sensorConfigLayouts.insert(m.key(),layout);
        }
    }

    ui->tab_sensorConfig->setLayout(masterSensorConfigLayout);
}
void ManageTunnelWidget::updateCurvesView(const QModelIndex &index)
{
    if (index.isValid())
    {
        QSqlRecord record = tunnelsModel->record(index.row());
        int tunnelid = record.value(0).toInt();
        //qDebug() << QObject::tr("update curvesView") << tunnelid;
        curvesModel = CurveDAO::getCurveDAOInstance()->getCurves(tunnelid);

        if (curvesModel == NULL)
        {
            qDebug() << QObject::tr("加载弯道不成功");
            return;
        }

        /*****************fanxiang*****************/
        // 先去掉原来的内容
        //ui->curvesView->clear();//此句不删除表格行数
        int tempk = ui->curvesView->rowCount();
        for (int k = 0; k < tempk; k++)
            ui->curvesView->removeRow(0);
        ui->curvesView->setRowCount(0);

        /* 填充表格内容 */
        QString itemstr;

        int columnCount = curvesModel->columnCount();
        int hideColumns = 2;
        for (int k = 0; k < curvesModel->rowCount(); k++)
        {
            int row = ui->curvesView->rowCount();
            //qDebug() << "cureves view row=" << row;
            ui->curvesView->setRowCount(row+1);

            // 表项
            bool static isStraight = true;
            bool static isLeft = true;
            for (int i = 0, j = 0; j < columnCount - hideColumns; i++)
            {
                record = curvesModel->record(k);
                itemstr = record.value(i).toString();
                QTableWidgetItem * tablewidgetitem = new QTableWidgetItem();

                // 去掉不显示数据(曲线编号,对应隧道和是否有效)
                if (i == Curve_tunnel_ID || i == Curve_is_valid)
                    continue;
                if (i == Curve_is_straight_std)
                    if (itemstr.compare("0") == 0)
                        isStraight = false;
                    else
                        isStraight = true;
                if (i == Curve_is_left_std)
                    if (itemstr.compare("0") == 0)
                        isLeft = false;
                    else
                        isLeft = true;
                if (i == Curve_is_straight_std)
                {
                    QComboBox *combo = new QComboBox();
                    combo->addItem(QObject::tr("是"));
                    combo->addItem(QObject::tr("否"));
                    if (itemstr.compare("0") == 0)
                        combo->setCurrentIndex(1); // 否
                    else if (itemstr.compare("1") == 0)
                        combo->setCurrentIndex(0); // 是
                    ui->curvesView->setCellWidget(k, j, combo);
                    connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changeCurveData()));
                }
                if (i == Curve_is_left_std)
                {
                    QComboBox *combo = new QComboBox();
                    combo->addItem(QObject::tr("左转"));
                    combo->addItem(QObject::tr("右转"));
                    if (itemstr.compare("0") == 0)
                        combo->setCurrentIndex(1); // 否
                    else if (itemstr.compare("1") == 0)
                        combo->setCurrentIndex(0); // 是
                    ui->curvesView->setCellWidget(k, j, combo);
                    connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changeCurveData()));
                }
                tablewidgetitem->setText(itemstr);
                ui->curvesView->setItem(k, j, tablewidgetitem);
                j++; // 非常关键
            }
Example #22
0
/**
 * Populate this dialog with the appropriate field editor widgets for the
 * database's columns, and set them to match the data in the specified row.
 *
 * @param rowId The data row to be edited or copied
 */
void RowEditor::addContent(int rowId)
{
    QScrollArea *sa = new QScrollArea(this);
    vbox->addWidget(sa);
    QWidget *grid = new QWidget();
    sa->setWidgetResizable(true);
    colNames = db->listColumns();
    int count = colNames.count();
    QGridLayout *layout = Factory::gridLayout(grid, true);
    QStringList values;
    if (rowId != -1) {
        values = db->getRow(rowId);
    }
    else {
        for (int i = 0; i < count; i++) {
            values.append(db->getDefault(colNames[i]));
        }
    }
    initialFocus = 0;
    colTypes = db->listTypes();
    for (int i = 0; i < count; i++) {
        QString name = colNames[i];
        int type = colTypes[i];
        layout->addWidget(new QLabel(name + " ", grid), i, 0);
        if (type == BOOLEAN) {
            QCheckBox *box = new QCheckBox(grid);
            layout->addWidget(box, i, 1);
            if (values[i].toInt()) {
                box->setChecked(true);
            }
            checkBoxes.append(box);
        }
        else if (type == INTEGER || type == FLOAT) {
            NumberWidget *widget = new NumberWidget(type, grid);
            layout->addWidget(widget, i, 1);
            widget->setValue(values[i]);
            numberWidgets.append(widget);
            if (!initialFocus) {
                initialFocus = widget;
            }
        }
        else if (type == NOTE) {
            NoteButton *button = new NoteButton(name, grid);
            layout->addWidget(button, i, 1);
            button->setContent(values[i]);
            noteButtons.append(button);
        }
        else if (type == DATE) {
            DateWidget *widget = new DateWidget(grid);
            layout->addWidget(widget, i, 1);
            widget->setDate(values[i].toInt());
            dateWidgets.append(widget);
        }
        else if (type == TIME) {
            TimeWidget *widget = new TimeWidget(grid);
            layout->addWidget(widget, i, 1);
            int defaultTime = values[i].toInt();
            if (defaultTime == 0) {
                defaultTime = -2;
            }
            widget->setTime(defaultTime);
            timeWidgets.append(widget);
        }
        else if (type == CALC) {
            CalcWidget *widget = new CalcWidget(db, name, colNames, this, grid);
            layout->addWidget(widget, i, 1);
            widget->setValue(values[i]);
            calcWidgets.append(widget);
        }
        else if (type == SEQUENCE) {
            QLabel *label = new QLabel(values[i], grid);
            layout->addWidget(label, i, 1);
            sequenceLabels.append(label);
        }
        else if (type == IMAGE) {
            ImageSelector *widget = new ImageSelector(db, grid);
            layout->addWidget(widget, i, 1);
            widget->setField(rowId, name);
            widget->setFormat(values[i]);
            imageSelectors.append(widget);
        }
        else if (type >= FIRST_ENUM) {
            QComboBox *combo = new QComboBox(grid);
            layout->addWidget(combo, i, 1);
            QStringList options = db->listEnumOptions(type);
            combo->addItems(options);
            int index = options.indexOf(values[i]);
            combo->setCurrentIndex(index);
            comboBoxes.append(combo);
        }
        else {
            DynamicEdit *edit = new DynamicEdit(grid);
            layout->addWidget(edit, i, 1);
            edit->setPlainText(values[i]);
            dynamicEdits.append(edit);
            if (!initialFocus) {
                initialFocus = edit;
            }
        }
    }
    layout->addWidget(new QWidget(grid), count, 0, 1, 2);
    layout->setRowStretch(count, 1);
    sa->setWidget(grid);

    finishLayout(true, true, 400, 400);
}
Example #23
0
AerolabWindow::AerolabWindow(MainWindow *mainWindow) :
  GcWindow(mainWindow), mainWindow(mainWindow) {
    setInstanceName("Aerolab Window");
    setControls(NULL);

  // Aerolab tab layout:
  QVBoxLayout *vLayout      = new QVBoxLayout;
  QHBoxLayout *cLayout      = new QHBoxLayout;

  // Plot:
  aerolab = new Aerolab(this, mainWindow);

  // Left controls layout:
  QVBoxLayout *leftControls  =  new QVBoxLayout;
  QFontMetrics metrics(QApplication::font());
  int labelWidth1 = metrics.width("Crr") + 10;

  // Crr:
  QHBoxLayout *crrLayout = new QHBoxLayout;
  QLabel *crrLabel = new QLabel(tr("Crr"), this);
  crrLabel->setFixedWidth(labelWidth1);
  crrLineEdit = new QLineEdit();
  crrLineEdit->setFixedWidth(75);
  crrLineEdit->setText(QString("%1").arg(aerolab->getCrr()) );
  /*crrQLCDNumber    = new QLCDNumber(7);
  crrQLCDNumber->setMode(QLCDNumber::Dec);
  crrQLCDNumber->setSmallDecimalPoint(false);
  crrQLCDNumber->setSegmentStyle(QLCDNumber::Flat);
  crrQLCDNumber->display(QString("%1").arg(aerolab->getCrr()) );*/
  crrSlider = new QSlider(Qt::Horizontal);
  crrSlider->setTickPosition(QSlider::TicksBelow);
  crrSlider->setTickInterval(1000);
  crrSlider->setMinimum(1000);
  crrSlider->setMaximum(10000);
  crrSlider->setValue(aerolab->intCrr());
  crrLayout->addWidget( crrLabel );
  crrLayout->addWidget( crrLineEdit );
  //crrLayout->addWidget( crrQLCDNumber );
  crrLayout->addWidget( crrSlider );

  // CdA:
  QHBoxLayout *cdaLayout = new QHBoxLayout;
  QLabel *cdaLabel = new QLabel(tr("CdA"), this);
  cdaLabel->setFixedWidth(labelWidth1);
  cdaLineEdit = new QLineEdit();
  cdaLineEdit->setFixedWidth(75);
  cdaLineEdit->setText(QString("%1").arg(aerolab->getCda()) );
  /*cdaQLCDNumber    = new QLCDNumber(7);
  cdaQLCDNumber->setMode(QLCDNumber::Dec);
  cdaQLCDNumber->setSmallDecimalPoint(false);
  cdaQLCDNumber->setSegmentStyle(QLCDNumber::Flat);
  cdaQLCDNumber->display(QString("%1").arg(aerolab->getCda()) );*/
  cdaSlider = new QSlider(Qt::Horizontal);
  cdaSlider->setTickPosition(QSlider::TicksBelow);
  cdaSlider->setTickInterval(100);
  cdaSlider->setMinimum(1);
  cdaSlider->setMaximum(6000);
  cdaSlider->setValue(aerolab->intCda());
  cdaLayout->addWidget( cdaLabel );
  //cdaLayout->addWidget( cdaQLCDNumber );
  cdaLayout->addWidget( cdaLineEdit );
  cdaLayout->addWidget( cdaSlider );

  // Eta:
  QHBoxLayout *etaLayout = new QHBoxLayout;
  QLabel *etaLabel = new QLabel(tr("Eta"), this);
  etaLabel->setFixedWidth(labelWidth1);
  etaLineEdit = new QLineEdit();
  etaLineEdit->setFixedWidth(75);
  etaLineEdit->setText(QString("%1").arg(aerolab->getEta()) );
  /*etaQLCDNumber    = new QLCDNumber(7);
  etaQLCDNumber->setMode(QLCDNumber::Dec);
  etaQLCDNumber->setSmallDecimalPoint(false);
  etaQLCDNumber->setSegmentStyle(QLCDNumber::Flat);
  etaQLCDNumber->display(QString("%1").arg(aerolab->getEta()) );*/
  etaSlider = new QSlider(Qt::Horizontal);
  etaSlider->setTickPosition(QSlider::TicksBelow);
  etaSlider->setTickInterval(1000);
  etaSlider->setMinimum(8000);
  etaSlider->setMaximum(12000);
  etaSlider->setValue(aerolab->intEta());
  etaLayout->addWidget( etaLabel );
  etaLayout->addWidget( etaLineEdit );
  //etaLayout->addWidget( etaQLCDNumber );
  etaLayout->addWidget( etaSlider );

  // Add to leftControls:
  leftControls->addLayout( crrLayout );
  leftControls->addLayout( cdaLayout );
  leftControls->addLayout( etaLayout );

  // Right controls layout:
  QVBoxLayout *rightControls  =  new QVBoxLayout;
  int labelWidth2 = metrics.width("Total Mass (kg)") + 10;

  // Total mass:
  QHBoxLayout *mLayout = new QHBoxLayout;
  QLabel *mLabel = new QLabel(tr("Total Mass (kg)"), this);
  mLabel->setFixedWidth(labelWidth2);
  mLineEdit = new QLineEdit();
  mLineEdit->setFixedWidth(70);
  mLineEdit->setText(QString("%1").arg(aerolab->getTotalMass()) );
  /*mQLCDNumber    = new QLCDNumber(7);
  mQLCDNumber->setMode(QLCDNumber::Dec);
  mQLCDNumber->setSmallDecimalPoint(false);
  mQLCDNumber->setSegmentStyle(QLCDNumber::Flat);
  mQLCDNumber->display(QString("%1").arg(aerolab->getTotalMass()) );*/
  mSlider = new QSlider(Qt::Horizontal);
  mSlider->setTickPosition(QSlider::TicksBelow);
  mSlider->setTickInterval(1000);
  mSlider->setMinimum(3500);
  mSlider->setMaximum(15000);
  mSlider->setValue(aerolab->intTotalMass());
  mLayout->addWidget( mLabel );
  mLayout->addWidget( mLineEdit );
  //mLayout->addWidget( mQLCDNumber );
  mLayout->addWidget( mSlider );

  // Rho:
  QHBoxLayout *rhoLayout = new QHBoxLayout;
  QLabel *rhoLabel = new QLabel(tr("Rho (kg/m^3)"), this);
  rhoLabel->setFixedWidth(labelWidth2);
  rhoLineEdit = new QLineEdit();
  rhoLineEdit->setFixedWidth(70);
  rhoLineEdit->setText(QString("%1").arg(aerolab->getRho()) );
  /*rhoQLCDNumber    = new QLCDNumber(7);
  rhoQLCDNumber->setMode(QLCDNumber::Dec);
  rhoQLCDNumber->setSmallDecimalPoint(false);
  rhoQLCDNumber->setSegmentStyle(QLCDNumber::Flat);
  rhoQLCDNumber->display(QString("%1").arg(aerolab->getRho()) );*/
  rhoSlider = new QSlider(Qt::Horizontal);
  rhoSlider->setTickPosition(QSlider::TicksBelow);
  rhoSlider->setTickInterval(1000);
  rhoSlider->setMinimum(9000);
  rhoSlider->setMaximum(14000);
  rhoSlider->setValue(aerolab->intRho());
  rhoLayout->addWidget( rhoLabel );
  rhoLayout->addWidget( rhoLineEdit );
  //rhoLayout->addWidget( rhoQLCDNumber );
  rhoLayout->addWidget( rhoSlider );

  // Elevation offset:
  QHBoxLayout *eoffsetLayout = new QHBoxLayout;
  QLabel *eoffsetLabel = new QLabel(tr("Eoffset (m)"), this);
  eoffsetLabel->setFixedWidth(labelWidth2);
  eoffsetLineEdit = new QLineEdit();
  eoffsetLineEdit->setFixedWidth(70);
  eoffsetLineEdit->setText(QString("%1").arg(aerolab->getEoffset()) );
  /*eoffsetQLCDNumber    = new QLCDNumber(7);
  eoffsetQLCDNumber->setMode(QLCDNumber::Dec);
  eoffsetQLCDNumber->setSmallDecimalPoint(false);
  eoffsetQLCDNumber->setSegmentStyle(QLCDNumber::Flat);
  eoffsetQLCDNumber->display(QString("%1").arg(aerolab->getEoffset()) );*/
  eoffsetSlider = new QSlider(Qt::Horizontal);
  eoffsetSlider->setTickPosition(QSlider::TicksBelow);
  eoffsetSlider->setTickInterval(20000);
  eoffsetSlider->setMinimum(-30000);
  eoffsetSlider->setMaximum(250000);
  eoffsetSlider->setValue(aerolab->intEoffset());
  eoffsetLayout->addWidget( eoffsetLabel );
  eoffsetLayout->addWidget( eoffsetLineEdit );
  //eoffsetLayout->addWidget( eoffsetQLCDNumber );
  eoffsetLayout->addWidget( eoffsetSlider );

  QCheckBox *eoffsetAuto = new QCheckBox(tr("eoffset auto"), this);
  eoffsetAuto->setCheckState(Qt::Checked);
  eoffsetLayout->addWidget(eoffsetAuto);

  QHBoxLayout *smoothLayout = new QHBoxLayout;
  QComboBox *comboDistance = new QComboBox();
  comboDistance->addItem(tr("X Axis Shows Time"));
  comboDistance->addItem(tr("X Axis Shows Distance"));
  comboDistance->setCurrentIndex(1);
  smoothLayout->addWidget(comboDistance);

  QPushButton *btnEstCdACrr = new QPushButton(tr("&Estimate CdA and Crr"), this);
  smoothLayout->addWidget(btnEstCdACrr);

  // Add to leftControls:
  rightControls->addLayout( mLayout );
  rightControls->addLayout( rhoLayout );
  rightControls->addLayout( eoffsetLayout );
  rightControls->addLayout( smoothLayout );


  // Assemble controls layout:
  cLayout->addLayout(leftControls);
  cLayout->addLayout(rightControls);

  // Zoomer:
  allZoomer = new QwtPlotZoomer(aerolab->canvas());
  allZoomer->setRubberBand(QwtPicker::RectRubberBand);
  allZoomer->setTrackerMode(QwtPicker::AlwaysOff);
  allZoomer->setEnabled(true);
  allZoomer->setMousePattern( QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier );
  allZoomer->setMousePattern( QwtEventPattern::MouseSelect3, Qt::RightButton );

  // SIGNALs to SLOTs:
  //connect(mainWindow, SIGNAL(rideSelected()), this, SLOT(rideSelected()));
  connect(this, SIGNAL(rideItemChanged(RideItem*)), this, SLOT(rideSelected()));
  connect(crrSlider, SIGNAL(valueChanged(int)),this, SLOT(setCrrFromSlider()));
  connect(crrLineEdit, SIGNAL(textChanged(const QString)), this, SLOT(setCrrFromText(const QString)));
  connect(cdaSlider, SIGNAL(valueChanged(int)), this, SLOT(setCdaFromSlider()));
  connect(cdaLineEdit, SIGNAL(textChanged(const QString)), this, SLOT(setCdaFromText(const QString)));
  connect(mSlider, SIGNAL(valueChanged(int)),this, SLOT(setTotalMassFromSlider()));
  connect(mLineEdit, SIGNAL(textChanged(const QString)), this, SLOT(setTotalMassFromText(const QString)));
  connect(rhoSlider, SIGNAL(valueChanged(int)), this, SLOT(setRhoFromSlider()));
  connect(rhoLineEdit, SIGNAL(textChanged(const QString)), this, SLOT(setRhoFromText(const QString)));
  connect(etaSlider, SIGNAL(valueChanged(int)), this, SLOT(setEtaFromSlider()));
  connect(etaLineEdit, SIGNAL(textChanged(const QString)), this, SLOT(setEtaFromText(const QString)));
  connect(eoffsetSlider, SIGNAL(valueChanged(int)), this, SLOT(setEoffsetFromSlider()));
  connect(eoffsetLineEdit, SIGNAL(textChanged(const QString)), this, SLOT(setEoffsetFromText(const QString)));
  connect(eoffsetAuto, SIGNAL(stateChanged(int)), this, SLOT(setAutoEoffset(int)));
  connect(comboDistance, SIGNAL(currentIndexChanged(int)), this, SLOT(setByDistance(int)));
  connect(btnEstCdACrr, SIGNAL(clicked()), this, SLOT(doEstCdACrr()));
  connect(mainWindow, SIGNAL(configChanged()), aerolab, SLOT(configChanged()));
  connect(mainWindow, SIGNAL(configChanged()), this, SLOT(configChanged()));
  connect(mainWindow, SIGNAL(intervalSelected() ), this, SLOT(intervalSelected()));
  connect(mainWindow, SIGNAL(intervalZoom(IntervalItem*) ), this, SLOT(zoomInterval(IntervalItem*)));
  connect(allZoomer, SIGNAL( zoomed(const QRectF) ), this, SLOT(zoomChanged()));


  // Build the tab layout:
  vLayout->addWidget(aerolab);
  vLayout->addLayout(cLayout);
  setLayout(vLayout);


  // tooltip on hover over point
  //************************************
    aerolab->tooltip = new LTMToolTip( QwtPlot::xBottom,
                                       QwtPlot::yLeft,
                                       QwtPicker::VLineRubberBand,
                                       QwtPicker::AlwaysOn,
                                       aerolab->canvas(),
                                       ""
                                     );
    aerolab->tooltip->setRubberBand( QwtPicker::VLineRubberBand );
    aerolab->tooltip->setMousePattern( QwtEventPattern::MouseSelect1, Qt::LeftButton, Qt::ShiftModifier );
    aerolab->tooltip->setTrackerPen( QColor( Qt::black ) );
    QColor inv( Qt::white );
    inv.setAlpha( 0 );
    aerolab->tooltip->setRubberBandPen( inv );
    aerolab->tooltip->setEnabled( true );
    aerolab->_canvasPicker = new LTMCanvasPicker( aerolab );

    connect( aerolab->_canvasPicker, SIGNAL( pointHover( QwtPlotCurve*, int ) ),
             aerolab,                SLOT  ( pointHover( QwtPlotCurve*, int ) ) );


  configChanged(); // pickup colors etc
}
MouseSettingsPage::MouseSettingsPage(AntiMicroSettings *settings, QWidget *parent) :
    QWizardPage(parent)
{
    this->settings = settings;

    setTitle(tr("Mouse Settings"));
    setSubTitle(tr("Customize settings used for mouse emulation"));
    QVBoxLayout *tempMainLayout = new QVBoxLayout;
    setLayout(tempMainLayout);

#ifdef Q_OS_WIN
    QCheckBox *disablePrecision = new QCheckBox(tr("Disable Enhance Pointer Precision"));
    disablePrecision->setToolTip(tr("Disable the \"Enhanced Pointer Precision\" Windows setting\n"
                                    "while antimicro is running. Disabling \"Enhanced Pointer Precision\"\n"
                                    "will allow mouse movement within antimicro to be more\n"
                                    "precise."));
    tempMainLayout->addWidget(disablePrecision);
    tempMainLayout->addSpacerItem(new QSpacerItem(10, 10));
    registerField("disableEnhancePrecision", disablePrecision);
#endif

    QGroupBox *smoothingGroupBox = new QGroupBox(tr("Smoothing"));
    smoothingGroupBox->setCheckable(true);
    smoothingGroupBox->setChecked(false);
    registerField("mouseSmoothing", smoothingGroupBox, "checked", SIGNAL(toggled(bool)));

    layout()->addWidget(smoothingGroupBox);

    QVBoxLayout *tempVLayout = new QVBoxLayout;

    QHBoxLayout *tempHLayout = new QHBoxLayout;
    QLabel *tempLabel = new QLabel(tr("History Buffer:"));
    QSpinBox *tempSpinBox = new QSpinBox;
    tempSpinBox->setMinimum(1);
    tempSpinBox->setMaximum(30);
    tempSpinBox->setValue(10);
    tempLabel->setBuddy(tempSpinBox);
    registerField("historyBuffer", tempSpinBox);

    tempHLayout->addWidget(tempLabel);
    tempHLayout->addWidget(tempSpinBox);
    tempVLayout->addLayout(tempHLayout);

    tempHLayout = new QHBoxLayout;
    tempLabel = new QLabel(tr("Weight Modifier:"));
    QDoubleSpinBox *tempDoubleSpinBox = new QDoubleSpinBox;
    tempDoubleSpinBox->setMinimum(0.0);
    tempDoubleSpinBox->setMaximum(1.0);
    tempDoubleSpinBox->setValue(0.20);
    tempDoubleSpinBox->setSingleStep(0.10);
    tempLabel->setBuddy(tempDoubleSpinBox);
    registerField("weightModifier", tempDoubleSpinBox);

    tempHLayout->addWidget(tempLabel);
    tempHLayout->addWidget(tempDoubleSpinBox);
    tempVLayout->addLayout(tempHLayout);

    smoothingGroupBox->setLayout(tempVLayout);

    tempHLayout = new QHBoxLayout;
    tempLabel = new QLabel(tr("Refresh Rate:"));
    QComboBox *tempComboBox = new QComboBox;

    for (int i = 1; i <= JoyButton::MAXIMUMMOUSEREFRESHRATE; i++)
    {
        tempComboBox->addItem(QString("%1 ms").arg(i), i);
    }

    int refreshIndex = tempComboBox->findData(JoyButton::getMouseRefreshRate());
    if (refreshIndex >= 0)
    {
        tempComboBox->setCurrentIndex(refreshIndex);
    }

    tempComboBox->setToolTip(tr("The refresh rate is the amount of time that will elapse\n"
                                "in between mouse events. Please be cautious when\n"
                                "editing this setting as it will cause the program to use\n"
                                "more CPU power. Setting this value too low can cause\n"
                                "system instability. Please test the setting before using\n"
                                "it unattended."));
    tempLabel->setBuddy(tempComboBox);
    registerField("mouseRefreshRate", tempComboBox);

    tempHLayout->addWidget(tempLabel);
    tempHLayout->addWidget(tempComboBox);
    tempMainLayout->addSpacerItem(new QSpacerItem(10, 10));
    tempMainLayout->addLayout(tempHLayout);
}
QList<QPair<QLabel*, QWidget*> > QgsVectorLayerSaveAsDialog::createControls( const QMap<QString, QgsVectorFileWriter::Option*>& options )
{
  QList<QPair<QLabel*, QWidget*> > controls;
  QMap<QString, QgsVectorFileWriter::Option*>::ConstIterator it;

  for ( it = options.constBegin(); it != options.constEnd(); ++it )
  {
    QgsVectorFileWriter::Option *option = it.value();
    QLabel *label = new QLabel( it.key() );
    QWidget *control = 0;
    switch ( option->type )
    {
      case QgsVectorFileWriter::Int:
      {
        QgsVectorFileWriter::IntOption* opt = dynamic_cast<QgsVectorFileWriter::IntOption*>( option );
        QSpinBox* sb = new QSpinBox();
        sb->setObjectName( it.key() );
        sb->setValue( opt->defaultValue );
        control = sb;
        break;
      }

      case QgsVectorFileWriter::Set:
      {
        QgsVectorFileWriter::SetOption* opt = dynamic_cast<QgsVectorFileWriter::SetOption*>( option );
        QComboBox* cb = new QComboBox();
        cb->setObjectName( it.key() );
        Q_FOREACH ( const QString& val, opt->values )
        {
          cb->addItem( val, val );
        }
        if ( opt->allowNone )
          cb->addItem( tr( "<Default>" ), QVariant( QVariant::String ) );
        int idx = cb->findText( opt->defaultValue );
        if ( idx == -1 )
          idx = cb->findData( QVariant( QVariant::String ) );
        cb->setCurrentIndex( idx );
        control = cb;
        break;
      }

      case QgsVectorFileWriter::String:
      {
        QgsVectorFileWriter::StringOption* opt = dynamic_cast<QgsVectorFileWriter::StringOption*>( option );
        QLineEdit* le = new QLineEdit( opt->defaultValue );
        le->setObjectName( it.key() );
        control = le;
        break;
      }

      case QgsVectorFileWriter::Hidden:
        control = 0;
        break;
    }

    if ( control )
    {
      // Pack the tooltip in some html element, so it gets linebreaks.
      label->setToolTip( QString( "<p>%1</p>" ).arg( option->docString ) );
      control->setToolTip( QString( "<p>%1</p>" ).arg( option->docString ) );

      controls << QPair<QLabel*, QWidget*>( label, control );
    }
  }

  return controls;
}
Example #26
0
//-----------------------------------------------------------------------------
void DatPanel::newdat()
{
	QLabel *l;
	QLineEdit *f1, *f2;
	QPushButton *b;
	QDialog *d = new QDialog(this);
	d->setWindowTitle(tr("UDAV - make new data"));
	QVBoxLayout *v = new QVBoxLayout(d);
	QComboBox *c = new QComboBox(d);	v->addWidget(c);
	c->addItem(tr("Sum along direction(s)"));
	c->addItem(tr("Min along direction(s)"));
	c->addItem(tr("Max along direction(s)"));
	c->addItem(tr("Momentum along 'x' for function"));
	c->addItem(tr("Momentum along 'y' for function"));
	c->addItem(tr("Momentum along 'z' for function"));
	c->setCurrentIndex(0);

	f1 = new QLineEdit("z",d);	v->addWidget(f1);
	QCheckBox *cb = new QCheckBox(tr("Put into this data array"), d);	v->addWidget(cb);
	l = new QLabel(tr("or enter name for new variable"), d);	v->addWidget(l);
	f2 = new QLineEdit(d);		v->addWidget(f2);
	QHBoxLayout *h = new QHBoxLayout();	v->addLayout(h);	h->addStretch(1);
	b = new QPushButton(tr("Cancel"), d);	h->addWidget(b);
	connect(b, SIGNAL(clicked()), d, SLOT(reject()));
	b = new QPushButton(tr("OK"), d);		h->addWidget(b);
	connect(b, SIGNAL(clicked()), d, SLOT(accept()));
	b->setDefault(true);
	// now execute dialog and get values
	bool res = d->exec();
	QString 	val = f1->text(), mgl;
	int k = c->currentIndex();
	QString self = QString::fromWCharArray(var->s.c_str());
	if(res)
	{
		if(k<0)
		{
			QMessageBox::warning(d, tr("UDAV - make new data"),
				tr("No action is selected. Do nothing."));
			return;
		}
		if(val.isEmpty())
		{
			QMessageBox::warning(d, tr("UDAV - make new data"),
				tr("No direction/formula is entered. Do nothing."));
			return;
		}
		if(cb->isChecked())	k += 6;
		QString name = f2->text();
		switch(k)
		{
		case 0:	mgl = "sum "+name+" "+self+" '"+val+"'";	break;
		case 1:	mgl = "min "+name+" "+self+" '"+val+"'";	break;
		case 2:	mgl = "max "+name+" "+self+" '"+val+"'";	break;
		case 3:	mgl = "momentum "+name+" "+self+" 'x' '"+val+"'";	break;
		case 4:	mgl = "momentum "+name+" "+self+" 'y' '"+val+"'";	break;
		case 5:	mgl = "momentum "+name+" "+self+" 'z' '"+val+"'";	break;
		case 6:	mgl = "copy "+self+" {sum "+self+" '"+val+"'}";	break;
		case 7:	mgl = "copy "+self+" {min "+self+" '"+val+"'}";	break;
		case 8:	mgl = "copy "+self+" {max "+self+" '"+val+"'}";	break;
		case 9:	mgl = "copy "+self+" {momentum "+self+" 'x' '"+val+"'}";	break;
		case 10:	mgl = "copy "+self+" {momentum "+self+" 'y' '"+val+"'}";	break;
		case 11:	mgl = "copy "+self+" {momentum "+self+" 'z' '"+val+"'}";	break;
		}
	}
	if(!mgl.isEmpty())
	{
		mglGraph gr;
		parser.Execute(&gr,mgl.toLocal8Bit().constData());
		if(k>=6)	opers += mgl+"\n";
		updateDataItems();
	}
}
bool QgsAttributeEditor::setValue( QWidget *editor, QgsVectorLayer *vl, int idx, const QVariant &value )
{
  if ( !editor )
    return false;

  QgsVectorLayer::EditType editType = vl->editType( idx );
  const QgsField &field = vl->pendingFields()[idx];
  QVariant::Type myFieldType = field.type();

  QSettings settings;
  QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString();

  switch ( editType )
  {
    case QgsVectorLayer::Classification:
    case QgsVectorLayer::UniqueValues:
    case QgsVectorLayer::Enumeration:
    case QgsVectorLayer::ValueMap:
    case QgsVectorLayer::ValueRelation:
    {
      QVariant v = value;
      QComboBox *cb = qobject_cast<QComboBox *>( editor );
      if ( !cb )
        return false;

      if ( v.isNull() )
      {
        v = nullValue;
      }

      int idx = cb->findData( v );
      if ( idx < 0 )
        return false;

      cb->setCurrentIndex( idx );
    }
    break;

    case QgsVectorLayer::DialRange:
    case QgsVectorLayer::SliderRange:
    case QgsVectorLayer::EditRange:
    {
      if ( myFieldType == QVariant::Int )
      {
        if ( editType == QgsVectorLayer::EditRange )
        {
          QSpinBox *sb = qobject_cast<QSpinBox *>( editor );
          if ( !sb )
            return false;
          sb->setValue( value.toInt() );
        }
        else
        {
          QAbstractSlider *sl = qobject_cast<QAbstractSlider *>( editor );
          if ( !sl )
            return false;
          sl->setValue( value.toInt() );
        }
        break;
      }
      else if ( myFieldType == QVariant::Double )
      {
        QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox *>( editor );
        if ( !dsb )
          return false;
        dsb->setValue( value.toDouble() );
      }
    }

    case QgsVectorLayer::CheckBox:
    {
      QCheckBox *cb = qobject_cast<QCheckBox *>( editor );
      if ( cb )
      {
        QPair<QString, QString> states = vl->checkedState( idx );
        cb->setChecked( value == states.first );
        break;
      }
    }

    // fall-through

    case QgsVectorLayer::LineEdit:
    case QgsVectorLayer::UniqueValuesEditable:
    case QgsVectorLayer::Immutable:
    case QgsVectorLayer::UuidGenerator:
    default:
    {
      QLineEdit *le = qobject_cast<QLineEdit *>( editor );
      QTextEdit *te = qobject_cast<QTextEdit *>( editor );
      QPlainTextEdit *pte = qobject_cast<QPlainTextEdit *>( editor );
      if ( !le && !te && !pte )
        return false;

      QString text;
      if ( value.isNull() )
      {
        if ( myFieldType == QVariant::Int || myFieldType == QVariant::Double || myFieldType == QVariant::LongLong )
          text = "";
        else if ( editType == QgsVectorLayer::UuidGenerator )
          text = QUuid::createUuid().toString();
        else
          text = nullValue;
      }
      else
      {
        text = value.toString();
      }

      if ( le )
        le->setText( text );
      if ( te )
        te->setHtml( text );
      if ( pte )
        pte->setPlainText( text );
    }
    break;

    case QgsVectorLayer::FileName:
    case QgsVectorLayer::Calendar:
    {
      QLineEdit* le = qobject_cast<QLineEdit*>( editor );
      if ( !le )
      {
        le = editor->findChild<QLineEdit *>();
      }
      if ( !le )
      {
        return false;
      }
      le->setText( value.toString() );
    }
    break;
  }

  return true;
}
Example #28
0
//-----------------------------------------------------------------------------
void DatPanel::oper()
{
	QLineEdit *f1;
	QPushButton *b;
	QDialog *d = new QDialog(this);
	d->setWindowTitle(tr("UDAV - change data"));
	QVBoxLayout *v = new QVBoxLayout(d);
	QComboBox *c = new QComboBox(d);	v->addWidget(c);
	c->addItem(tr("Fill data by formula"));
	c->addItem(tr("Transpose data with new dimensions"));
	c->addItem(tr("Smooth data along direction(s)"));
	c->addItem(tr("Summarize data along direction(s)"));
	c->addItem(tr("Integrate data along direction(s)"));
	c->addItem(tr("Differentiate data along direction(s)"));
	c->addItem(tr("Laplace transform along direction(s)"));
	c->addItem(tr("Swap data along direction(s)"));
	c->addItem(tr("Mirror data along direction(s)"));
	c->addItem(tr("Sin-Fourier transform along direction(s)"));
	c->addItem(tr("Cos-Fourier transform along direction(s)"));
	c->addItem(tr("Hankel transform along direction(s)"));
	c->addItem(tr("Sew data along direction(s)"));
	c->addItem(tr("Find envelope along direction(s)"));
	c->setCurrentIndex(0);

	f1 = new QLineEdit("z",d);	v->addWidget(f1);
	QHBoxLayout *h = new QHBoxLayout();	v->addLayout(h);	h->addStretch(1);
	b = new QPushButton(tr("Cancel"), d);	h->addWidget(b);
	connect(b, SIGNAL(clicked()), d, SLOT(reject()));
	b = new QPushButton(tr("OK"), d);		h->addWidget(b);
	connect(b, SIGNAL(clicked()), d, SLOT(accept()));
	b->setDefault(true);
	// now execute dialog and get values
	bool res = d->exec();
	QString 	val = f1->text(), mgl;
	int k = c->currentIndex();
	QString self = QString::fromWCharArray(var->s.c_str());
	if(res)
	{
		if(k<0)
		{
			QMessageBox::warning(d, tr("UDAV - make new data"),
				tr("No action is selected. Do nothing."));
			return;
		}
		switch(k)
		{
		case 0:	mgl = "modify "+self+" '"+val+"'";	break;
		case 1:	mgl = "transpose "+self+" '"+val+"'";	break;
		case 2:	mgl = "smooth "+self+" '"+val+"'";	break;
		case 3:	mgl = "cumsum "+self+" '"+val+"'";	break;
		case 4:	mgl = "integrate "+self+" '"+val+"'";	break;
		case 5:	mgl = "diff "+self+" '"+val+"'";	break;
		case 6:	mgl = "diff2 "+self+" '"+val+"'";	break;
		case 7:	mgl = "swap "+self+" '"+val+"'";	break;
		case 8:	mgl = "mirror "+self+" '"+val+"'";	break;
		case 9:	mgl = "sinfft "+self+" '"+val+"'";	break;
		case 10:	mgl = "cosfft "+self+" '"+val+"'";	break;
		case 11:	mgl = "hankel "+self+" '"+val+"'";	break;
		case 12:	mgl = "sew "+self+" '"+val+"'";	break;
		case 13:	mgl = "envelop "+self+" '"+val+"'";	break;
		}
	}
	if(!mgl.isEmpty())
	{
		mglGraph gr;
		parser.Execute(&gr,mgl.toLocal8Bit().constData());
		opers += mgl+"\n";
		updateDataItems();
	}
}
Example #29
0
void AsciiOpenDlg::updateTable()
{
	m_ui->tableWidget->setEnabled(false);
	m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false);

	bool hadValidHeader = !m_headerLine.isEmpty();
	m_headerLine.clear();

	if (m_filename.isEmpty())
	{
		m_ui->tableWidget->clear();
		return;
	}
	//we open the file in ASCII mode
	QFile file(m_filename);
	if (!file.open(QFile::ReadOnly))
	{
		m_ui->tableWidget->clear();
		m_columnType.clear();
		return;
	}
	QTextStream stream(&file);

	//we skip first lines (if needed)
	{
		for (unsigned i = 0; i < m_skippedLines; ++i)
		{
			QString currentLine = stream.readLine();
			//we keep track of the first line
			if (i == 0)
				m_headerLine = currentLine;
		}
	}

	//if the old setup has less than 3 columns, we forget it
	if (m_columnsCount < 3)
	{
		m_ui->tableWidget->clear();
		m_columnType.clear();
		m_columnsCount = 0;
	}
	m_ui->tableWidget->setRowCount(DISPLAYED_LINES + 1);	//+1 for first line shifting

	unsigned lineCount = 0;			//number of lines read
	unsigned totalChars = 0;		//total read characters (for stats)
	unsigned columnsCount = 0;		//max columns count per line
	unsigned commentLines = 0;		//number of comments line skipped

	std::vector<bool> valueIsNumber;	//identifies columns with numbers only [mandatory]
	std::vector<bool> valueIsBelowOne;	//identifies columns with values between -1 and 1 only
	std::vector<bool> valueIsInteger;	//identifies columns with integer values only
	std::vector<bool> valueIsBelow255;	//identifies columns with integer values between 0 and 255 only

	QChar decimalPoint = QLocale().decimalPoint();
	QString currentLine = stream.readLine();
	while (lineCount < LINES_READ_FOR_STATS && !currentLine.isNull())
	{
		//we recognize "//" as the beginning of a comment
		if (!currentLine.startsWith("//")/* || !currentLine.startsWith("#")*/)
		{
			QStringList parts = currentLine.trimmed().split(m_separator, QString::SkipEmptyParts);
			if (lineCount < DISPLAYED_LINES)
			{
				unsigned partsCount = std::min(MAX_COLUMNS, static_cast<unsigned>(parts.size()));
				bool columnCountHasIncreased = (partsCount > columnsCount);

				//do we need to add one or several new columns?
				if (columnCountHasIncreased)
				{
					//we also extend vectors
					for (unsigned i = columnsCount; i < partsCount; ++i)
					{
						valueIsNumber.push_back(true);
						valueIsBelowOne.push_back(true);
						valueIsBelow255.push_back(true);
						valueIsInteger.push_back(true);
					}

					if (m_ui->tableWidget->columnCount() < static_cast<int>(partsCount))
					{
						//DGM: at this stage we must not reduce the table!
						//The first line is sometimes smaller than the next ones
						//and we want to keep the widgets/configuration for the
						//other columns!
						m_ui->tableWidget->setColumnCount(partsCount);
					}
					else if (m_ui->tableWidget->columnCount() > static_cast<int>(partsCount))
					{
						//remove the unnecessary cells!
						for (int i = static_cast<int>(partsCount); i < m_ui->tableWidget->columnCount(); ++i)
						{
							m_ui->tableWidget->setItem(lineCount + 1, i, 0);
						}
					}
					columnsCount = partsCount;
				}

				//we fill the current row with extracted parts
				for (unsigned i = 0; i < partsCount; ++i)
				{
					QTableWidgetItem* newItem = new QTableWidgetItem(parts[i]);

					//test values
					bool isANumber = false;
					double value = parts[i].toDouble(&isANumber);
					if (!isANumber)
					{
						valueIsNumber[i] = false;
						valueIsBelowOne[i] = false;
						valueIsInteger[i] = false;
						valueIsBelow255[i] = false;
						newItem->setBackground(QBrush(QColor(255, 160, 160)));
					}
					else
					{
						if (columnCountHasIncreased || (lineCount == 1 && !valueIsNumber[i]))
						{
							//the previous lines were probably header lines
							//we can forget about their content otherwise it will prevent us from detecting the right pattern
							valueIsNumber[i] = true;
							valueIsBelowOne[i] = true;
							valueIsInteger[i] = true;
							valueIsBelow255[i] = true;
						}
						valueIsBelowOne[i] = valueIsBelowOne[i] && (fabs(value) <= 1.0);
						valueIsInteger[i] = valueIsInteger[i] && !parts[i].contains(decimalPoint);
						valueIsBelow255[i] = valueIsBelow255[i] && valueIsInteger[i] && (value >= 0.0 && value <= 255.0);
					}

					m_ui->tableWidget->setItem(lineCount + 1, i, newItem); //+1 for first line shifting
				}
			}

			totalChars += currentLine.size() + 1; //+1 for return char at eol
			++lineCount;
		}
		else
		{
			if (m_skippedLines == 0 && commentLines == 0)
			{
				//if the very first line is a comment, then we force the user to skip it!
				//this way it will be considered as a header
				m_ui->spinBoxSkipLines->setMinimum(1);
				return;
			}
			++commentLines;
		}

		//read next line
		currentLine = stream.readLine();
	}

	file.close();

	//now we can reduce the table (if necessary)
	if (m_ui->tableWidget->columnCount() > static_cast<int>(columnsCount))
	{
		m_ui->tableWidget->setColumnCount(columnsCount);
	}

	//process header line
	if (!m_headerLine.isEmpty())
	{
		m_headerLine = m_headerLine.trimmed();
		int n = 0;
		while (n < m_headerLine.size() && m_headerLine.at(n) == '/')
		{
			++n;
		}
		if (n != 0)
		{
			m_headerLine.remove(0, n);
		}
		m_ui->headerLabel->setText(QString("Header: ") + m_headerLine);
		m_ui->headerLabel->setVisible(true);
	}
	else
	{
		m_ui->headerLabel->setVisible(false);
	}

	m_ui->commentLinesSkippedLabel->setVisible(commentLines != 0);
	if (commentLines)
	{
		m_ui->commentLinesSkippedLabel->setText(QString("+ %1 comment line(s) skipped").arg(commentLines));
	}

	if (lineCount == 0 || columnsCount == 0)
	{
		m_averageLineSize = -1.0;
		m_ui->tableWidget->clear();
		m_columnType.clear();
		return;
	}

	//average line size
	m_averageLineSize = static_cast<double>(totalChars) / lineCount;
	unsigned approximateTotalLineCount = static_cast<unsigned>(file.size() / m_averageLineSize);

	//we add a type selector for each column
	QStringList propsText;
	{
		propsText.reserve(ASCII_OPEN_DLG_TYPES_COUNT);
		for (unsigned i = 0; i < ASCII_OPEN_DLG_TYPES_COUNT; i++)
		{
			propsText << QString(ASCII_OPEN_DLG_TYPES_NAMES[i]);
		}
	}

	//remove unnecessary columns
	{
		while (columnsCount < m_columnsCount)
			m_ui->tableWidget->removeColumn(--m_columnsCount);
		if (m_columnType.size() > columnsCount)
			m_columnType.resize(columnsCount, UNKNOWN);
		for (unsigned i = lineCount + 1; i <= DISPLAYED_LINES; ++i)
			m_ui->tableWidget->removeRow(i);
	}

	//setup table and widgets
	{
		//Icons
		static const QIcon xIcon		(QString::fromUtf8(":/CC/images/typeXCoordinate.png"));
		static const QIcon yIcon		(QString::fromUtf8(":/CC/images/typeYCoordinate.png"));
		static const QIcon zIcon		(QString::fromUtf8(":/CC/images/typeZCoordinate.png"));
		static const QIcon NormIcon		(QString::fromUtf8(":/CC/images/typeNormal.png"));
		static const QIcon RGBIcon		(QString::fromUtf8(":/CC/images/typeRgbCcolor.png"));
		static const QIcon GreyIcon		(QString::fromUtf8(":/CC/images/typeGrayColor.png"));
		static const QIcon ScalarIcon	(QString::fromUtf8(":/CC/images/typeSF.png"));
		static const QIcon LabelIcon	(QString::fromUtf8(":/CC/images/dbLabelSymbol.png"));

		int columnWidth = (m_ui->tableWidget->width() * 9) / (columnsCount * 10);
		columnWidth = std::max(columnWidth, 80);

		for (unsigned i = 0; i < columnsCount; i++)
		{
			QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
			QComboBox* _columnHeader = columnHeaderWidget;
			if (!columnHeaderWidget)
			{
				columnHeaderWidget = new QComboBox();
				columnHeaderWidget->addItems(propsText);
				columnHeaderWidget->setMaxVisibleItems(ASCII_OPEN_DLG_TYPES_COUNT);
				columnHeaderWidget->setCurrentIndex(0);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_X, xIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Y, yIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Z, zIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NX, NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NY, NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NZ, NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_R, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_G, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_B, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Rf, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Gf, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Bf, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Grey, GreyIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32i, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32f, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Label, LabelIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Scalar, ScalarIcon);

				connect(columnHeaderWidget, SIGNAL(currentIndexChanged(int)), this, SLOT(columnsTypeHasChanged(int)));
			}

			while (m_columnType.size() <= static_cast<size_t>(i))
				m_columnType.push_back(UNKNOWN);
			assert(m_columnType.size() >= static_cast<size_t>(i));

			if (!_columnHeader)
				m_ui->tableWidget->setCellWidget(0, i, columnHeaderWidget);
			m_ui->tableWidget->setColumnWidth(i, columnWidth);

			//a non-numerical column can't be valid
			if (!valueIsNumber[i])
				m_columnType[i] = TEXT;
			else
				// we must do this to ensure we can get a correct result.
				// Otherwise, we may fail in such situations:
				//
				// FILE:
				// Line1   : $ gps file
				// Line2   : $ id name x y z
				// Line3   : 500
				// Line4   : 0    0001.JPG  753811.417453   4307200.381522      1957.803955
				// Linex   : ......
				// Line503 : 499  0500.JPG  753630.672714   4307195.433217      1957.803955
				// 
				// Description:
				// once we open the file, we will get a %m_columnType with 5 values of "TEXT"
				// then if we choose to skip the 3 first lines, we get a %valueIsNumber with 5 "true"
				// but the %m_columnType is still with 5 values of "TEXT" which leads to the failure!
				m_columnType[i] = UNKNOWN;
		}
	}
Example #30
0
void pPrincipal::on_InsertarC_clicked()
{
    if(!(indiceActual.parent().isValid()) && indiceActual.isValid()){
    QDialog dialogo(this);
    dialogo.setWindowTitle(tr("Ingresar nueva calificacion"));
    QFormLayout form(&dialogo);

    // Add some text above the fields
    form.addRow(new QLabel("Ingresa la informacion de la calificacion.\nSi desconoces tu nota, deja el valor en 0."));

    // Add the lineEdits with their respective labels
    QList<QWidget *> campos;
    for(int i = 0; i < 4; ++i) {
        QWidget *campo=0;
        QString label;
        switch(i)
        {
            case 0:
            {
            QLineEdit * temp;
            temp=new QLineEdit(this);
            temp->setText("");
            //qDebug() << "Entre al caso "<< i << endl;
            campo=temp;
            label=QString("Nombre:");
            break;
            }
            case 1:
            {
            QDoubleSpinBox * temp;
            temp=new QDoubleSpinBox(this);
            temp->setRange(0.0,5.0);
            temp->setDecimals(1);
            temp->setSingleStep(0.5);
            temp->setValue(3.5);
            //qDebug() << "Entre al caso "<< i << endl;
            campo=temp;
            label=QString("Nota:");
            break;
            }
            case 2:
            {
            QSpinBox *temp;
            temp = new QSpinBox(this);
            temp->setRange(0,100);
            temp->setValue(20);
            campo=temp;
            label=QString("Porcentaje:");
            break;
            }
            case 3:
            {
            QComboBox * temp;
            temp = new QComboBox(this);
            QStringList items;
            items  << tr("Facil") << tr("Medio") << tr("Dificil");
            temp->addItems(items);
            temp->setCurrentIndex(1);
            campo=temp;
            label=QString("Dificultad:");
            break;
        }
        }
        form.addRow(label, campo);

        campos << campo;
    }
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                               Qt::Horizontal, &dialogo);
    form.addRow(&buttonBox);
    QObject::connect(&buttonBox, SIGNAL(accepted()), &dialogo, SLOT(accept()));
    QObject::connect(&buttonBox, SIGNAL(rejected()), &dialogo, SLOT(reject()));
    if (dialogo.exec()==QDialog::Accepted)
        {
           QList<QVariant> propiedades;
           propiedades.append(((QLineEdit *)campos[0])->text());
           propiedades.append(((QDoubleSpinBox *)campos[1])->value());
           propiedades.append(((QSpinBox *)campos[2])->value());
           propiedades.append(((QComboBox *)campos[3])->currentIndex());
           if(propiedades.at(0)!="")
           {
            modelo->setData(indiceActual,propiedades,0);
            //actualizarModelo();
           }
        }
    }
}