Example #1
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();
	}
}
QVariant UIPropertyGetters::DefaultGetter(QWidget* editor, SettingsPropertyMapper::WidgetType editorType, SettingsPropertyMapper::PropertyType)
{
	switch (editorType)
	{
		case SettingsPropertyMapper::CHECKBOX:
		{
			QCheckBox* pCheckBox = qobject_cast<QCheckBox*>(editor);
			if (pCheckBox == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pCheckBox->isChecked());
		}
		case SettingsPropertyMapper::RADIOBUTTON:
		{
			QRadioButton* pRadioButton = qobject_cast<QRadioButton*>(editor);
			if (pRadioButton == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pRadioButton->isChecked());
		}
		case SettingsPropertyMapper::CHECKABLE_GROUPBOX:
		{
			QGroupBox* pGroupBox = qobject_cast<QGroupBox*>(editor);
			if (pGroupBox == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			if (!pGroupBox->isCheckable())
			{
				qCritical() << "Given QGroupBox is not checkable";
			}
			return QVariant::fromValue(pGroupBox->isChecked());
		}
		case SettingsPropertyMapper::LINE_EDIT:
		{
			QLineEdit* pLineEdit = qobject_cast<QLineEdit*>(editor);
			if (pLineEdit == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pLineEdit->text());
		}
		case SettingsPropertyMapper::TEXT_EDIT:
		{
			QTextEdit* pTextEdit = qobject_cast<QTextEdit*>(editor);
			if (pTextEdit == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pTextEdit->toPlainText());
		}
		case SettingsPropertyMapper::COMBOBOX:
		{
			QComboBox* pComboBox = qobject_cast<QComboBox*>(editor);
			if (pComboBox == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pComboBox->currentIndex());
		}
		case SettingsPropertyMapper::SPINBOX:
		{
			QSpinBox* pSpinBox = qobject_cast<QSpinBox*>(editor);
			if (pSpinBox == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pSpinBox->value());
		}
		case SettingsPropertyMapper::DOUBLE_SPINBOX:
		{
			QDoubleSpinBox* pDoubleSpinBox = qobject_cast<QDoubleSpinBox*>(editor);
			if (pDoubleSpinBox == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pDoubleSpinBox->value());
		}
		case SettingsPropertyMapper::TIME_EDIT:
		{
			QTimeEdit* pTimeEdit = qobject_cast<QTimeEdit*>(editor);
			if (pTimeEdit == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pTimeEdit->time());
		}
		case SettingsPropertyMapper::DATETIME_EDIT:
		{
			QDateTimeEdit* pDateTimeEdit = qobject_cast<QDateTimeEdit*>(editor);
			if (pDateTimeEdit == NULL)
			{
				qCritical() << "Invalid editor given";
				return QVariant();
			}
			return QVariant::fromValue(pDateTimeEdit->dateTime());
		}
		default:
		{
			return QVariant();
		}
	}
}
Example #3
0
void MainWindow::setupUi()
{
    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->setSpacing(0);
    mainLayout->setMargin(0);
    setLayout(mainLayout);

    mpPlayerLayout = new QVBoxLayout();
    mpControl = new QWidget(this);
    mpControl->setMaximumHeight(25);

    //mpPreview = new QLable(this);

    mpTimeSlider = new Slider(mpControl);
    mpTimeSlider->setDisabled(true);
    //mpTimeSlider->setFixedHeight(8);
    mpTimeSlider->setMaximumHeight(8);
    mpTimeSlider->setTracking(true);
    mpTimeSlider->setOrientation(Qt::Horizontal);
    mpTimeSlider->setMinimum(0);
    mpCurrent = new QLabel(mpControl);
    mpCurrent->setToolTip(tr("Current time"));
    mpCurrent->setMargin(2);
    mpCurrent->setText("00:00:00");
    mpEnd = new QLabel(mpControl);
    mpEnd->setToolTip(tr("Duration"));
    mpEnd->setMargin(2);
    mpEnd->setText("00:00:00");
    mpTitle = new QLabel(mpControl);
    mpTitle->setToolTip(tr("Render engine"));
    mpTitle->setText("QPainter");
    mpTitle->setIndent(8);
    mpSpeed = new QLabel("1.00");
    mpSpeed->setMargin(1);
    mpSpeed->setToolTip(tr("Speed. Ctrl+Up/Down"));

    mPlayPixmap = QPixmap(":/theme/button-play-pause.png");
    int w = mPlayPixmap.width(), h = mPlayPixmap.height();
    mPausePixmap = mPlayPixmap.copy(QRect(w/2, 0, w/2, h));
    mPlayPixmap = mPlayPixmap.copy(QRect(0, 0, w/2, h));
    qDebug("%d x %d", mPlayPixmap.width(), mPlayPixmap.height());
    mpPlayPauseBtn = new Button(mpControl);
    int a = qMin(w/2, h);
    const int kMaxButtonIconWidth = 20;
    const int kMaxButtonIconMargin = kMaxButtonIconWidth/3;
    a = qMin(a, kMaxButtonIconWidth);
    mpPlayPauseBtn->setIconWithSates(mPlayPixmap);
    mpPlayPauseBtn->setIconSize(QSize(a, a));
    mpPlayPauseBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);
    mpStopBtn = new Button(mpControl);
    mpStopBtn->setIconWithSates(QPixmap(":/theme/button-stop.png"));
    mpStopBtn->setIconSize(QSize(a, a));
    mpStopBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);
    mpBackwardBtn = new Button(mpControl);
    mpBackwardBtn->setIconWithSates(QPixmap(":/theme/button-rewind.png"));
    mpBackwardBtn->setIconSize(QSize(a, a));
    mpBackwardBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);
    mpForwardBtn = new Button(mpControl);
    mpForwardBtn->setIconWithSates(QPixmap(":/theme/button-fastforward.png"));
    mpForwardBtn->setIconSize(QSize(a, a));
    mpForwardBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);
    mpOpenBtn = new Button(mpControl);
    mpOpenBtn->setToolTip(tr("Open"));
    mpOpenBtn->setIconWithSates(QPixmap(":/theme/open_folder.png"));
    mpOpenBtn->setIconSize(QSize(a, a));
    mpOpenBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);

    mpInfoBtn = new Button();
    mpInfoBtn->setToolTip(QString("Media information. Not implemented."));
    mpInfoBtn->setIconWithSates(QPixmap(":/theme/info.png"));
    mpInfoBtn->setIconSize(QSize(a, a));
    mpInfoBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);
    mpCaptureBtn = new Button();
    mpCaptureBtn->setIconWithSates(QPixmap(":/theme/screenshot.png"));
    mpCaptureBtn->setIconSize(QSize(a, a));
    mpCaptureBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);
    mpVolumeBtn = new Button();
    mpVolumeBtn->setIconWithSates(QPixmap(":/theme/button-max-volume.png"));
    mpVolumeBtn->setIconSize(QSize(a, a));
    mpVolumeBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);

    mpVolumeSlider = new Slider();
    mpVolumeSlider->hide();
    mpVolumeSlider->setOrientation(Qt::Horizontal);
    mpVolumeSlider->setMinimum(0);
    const int kVolumeSliderMax = 100;
    mpVolumeSlider->setMaximum(kVolumeSliderMax);
    mpVolumeSlider->setMaximumHeight(8);
    mpVolumeSlider->setMaximumWidth(88);
    mpVolumeSlider->setValue(int(1.0/kVolumeInterval*qreal(kVolumeSliderMax)/100.0));
    setVolume();

    mpMenuBtn = new Button();
    mpMenuBtn->setAutoRaise(true);
    mpMenuBtn->setPopupMode(QToolButton::InstantPopup);

/*
    mpMenuBtn->setIconWithSates(QPixmap(":/theme/search-arrow.png"));
    mpMenuBtn->setIconSize(QSize(a, a));
    mpMenuBtn->setMaximumSize(a+kMaxButtonIconMargin+2, a+kMaxButtonIconMargin);
*/
    QMenu *subMenu = 0;
    QWidgetAction *pWA = 0;
    mpMenu = new QMenu(mpMenuBtn);
    mpMenu->addAction(tr("Open Url"), this, SLOT(openUrl()));
    //mpMenu->addAction(tr("Online channels"), this, SLOT(onTVMenuClick()));
    mpMenu->addSeparator();

    subMenu = new QMenu(tr("Play list"));
    mpMenu->addMenu(subMenu);
    mpPlayList = new PlayList(this);
    mpPlayList->setSaveFile(Config::instance().defaultDir() + "/playlist.qds");
    mpPlayList->load();
    connect(mpPlayList, SIGNAL(aboutToPlay(QString)), SLOT(play(QString)));
    pWA = new QWidgetAction(0);
    pWA->setDefaultWidget(mpPlayList);
    subMenu->addAction(pWA); //must add action after the widget action is ready. is it a Qt bug?

    subMenu = new QMenu(tr("History"));
    mpMenu->addMenu(subMenu);
    mpHistory = new PlayList(this);
    mpHistory->setMaxRows(20);
    mpHistory->setSaveFile(Config::instance().defaultDir() + "/history.qds");
    mpHistory->load();
    connect(mpHistory, SIGNAL(aboutToPlay(QString)), SLOT(play(QString)));
    pWA = new QWidgetAction(0);
    pWA->setDefaultWidget(mpHistory);
    subMenu->addAction(pWA); //must add action after the widget action is ready. is it a Qt bug?

    mpMenu->addSeparator();

    //mpMenu->addAction(tr("Report"))->setEnabled(false); //report bug, suggestions etc. using maillist?
    mpMenu->addAction(tr("About"), this, SLOT(about()));
    mpMenu->addAction(tr("Help"), this, SLOT(help()));
    mpMenu->addAction(tr("About Qt"), qApp, SLOT(aboutQt()));
    mpMenu->addAction(tr("Donate"), this, SLOT(donate()));
    mpMenu->addAction(tr("Setup"), this, SLOT(setup()));
    mpMenu->addSeparator();
    mpMenuBtn->setMenu(mpMenu);
    mpMenu->addSeparator();

    subMenu = new QMenu(tr("Speed"));
    mpMenu->addMenu(subMenu);
    QDoubleSpinBox *pSpeedBox = new QDoubleSpinBox(0);
    pSpeedBox->setRange(0.01, 20);
    pSpeedBox->setValue(1.0);
    pSpeedBox->setSingleStep(0.01);
    pSpeedBox->setCorrectionMode(QAbstractSpinBox::CorrectToPreviousValue);
    pWA = new QWidgetAction(0);
    pWA->setDefaultWidget(pSpeedBox);
    subMenu->addAction(pWA); //must add action after the widget action is ready. is it a Qt bug?

    subMenu = new ClickableMenu(tr("Repeat"));
    mpMenu->addMenu(subMenu);
    //subMenu->setEnabled(false);
    mpRepeatEnableAction = subMenu->addAction(tr("Enable"));
    mpRepeatEnableAction->setCheckable(true);
    connect(mpRepeatEnableAction, SIGNAL(toggled(bool)), SLOT(toggleRepeat(bool)));
    // TODO: move to a func or class
    mpRepeatBox = new QSpinBox(0);
    mpRepeatBox->setMinimum(-1);
    mpRepeatBox->setValue(-1);
    mpRepeatBox->setToolTip("-1: " + tr("infinity"));
    connect(mpRepeatBox, SIGNAL(valueChanged(int)), SLOT(setRepeateMax(int)));
    QLabel *pRepeatLabel = new QLabel(tr("Times"));
    QHBoxLayout *hb = new QHBoxLayout;
    hb->addWidget(pRepeatLabel);
    hb->addWidget(mpRepeatBox);
    QVBoxLayout *vb = new QVBoxLayout;
    vb->addLayout(hb);
    pRepeatLabel = new QLabel(tr("From"));
    mpRepeatA = new QTimeEdit();
    mpRepeatA->setDisplayFormat("HH:mm:ss");
    mpRepeatA->setToolTip(tr("negative value means from the end"));
    connect(mpRepeatA, SIGNAL(timeChanged(QTime)), SLOT(repeatAChanged(QTime)));
    hb = new QHBoxLayout;
    hb->addWidget(pRepeatLabel);
    hb->addWidget(mpRepeatA);
    vb->addLayout(hb);
    pRepeatLabel = new QLabel(tr("To"));
    mpRepeatB = new QTimeEdit();
    mpRepeatB->setDisplayFormat("HH:mm:ss");
    mpRepeatB->setToolTip(tr("negative value means from the end"));
    connect(mpRepeatB, SIGNAL(timeChanged(QTime)), SLOT(repeatBChanged(QTime)));
    hb = new QHBoxLayout;
    hb->addWidget(pRepeatLabel);
    hb->addWidget(mpRepeatB);
    vb->addLayout(hb);
    QWidget *wgt = new QWidget;
    wgt->setLayout(vb);

    pWA = new QWidgetAction(0);
    pWA->setDefaultWidget(wgt);
    pWA->defaultWidget()->setEnabled(false);
    subMenu->addAction(pWA); //must add action after the widget action is ready. is it a Qt bug?
    mpRepeatAction = pWA;

    mpMenu->addSeparator();

    subMenu = new ClickableMenu(tr("Subtitle"));
    mpMenu->addMenu(subMenu);
    QAction *act = subMenu->addAction(tr("Enable"));
    act->setCheckable(true);
    act->setChecked(mpSubtitle->isEnabled());
    connect(act, SIGNAL(toggled(bool)), SLOT(toggoleSubtitleEnabled(bool)));
    act = subMenu->addAction(tr("Auto load"));
    act->setCheckable(true);
    act->setChecked(mpSubtitle->autoLoad());
    connect(act, SIGNAL(toggled(bool)), SLOT(toggleSubtitleAutoLoad(bool)));
    subMenu->addAction(tr("Open"), this, SLOT(openSubtitle()));

    wgt = new QWidget();
    hb = new QHBoxLayout();
    wgt->setLayout(hb);
    hb->addWidget(new QLabel(tr("Engine")));
    QComboBox *box = new QComboBox();
    hb->addWidget(box);
    pWA = new QWidgetAction(0);
    pWA->setDefaultWidget(wgt);
    subMenu->addAction(pWA); //must add action after the widget action is ready. is it a Qt bug?
    box->addItem("FFmpeg", "FFmpeg");
    box->addItem("LibASS", "LibASS");
    connect(box, SIGNAL(activated(QString)), SLOT(setSubtitleEngine(QString)));
    mpSubtitle->setEngines(QStringList() << box->itemData(box->currentIndex()).toString());
    box->setToolTip(tr("FFmpeg supports more subtitles but only render plain text") + "\n" + tr("LibASS supports ass styles"));

    wgt = new QWidget();
    hb = new QHBoxLayout();
    wgt->setLayout(hb);
    hb->addWidget(new QLabel(tr("Charset")));
    box = new QComboBox();
    hb->addWidget(box);
    pWA = new QWidgetAction(0);
    pWA->setDefaultWidget(wgt);
    subMenu->addAction(pWA); //must add action after the widget action is ready. is it a Qt bug?
    box->addItem(tr("Auto detect"), "AutoDetect");
    box->addItem(tr("System"), "System");
    foreach (const QByteArray& cs, QTextCodec::availableCodecs()) {
        box->addItem(cs, cs);
    }
Example #4
0
void ActionZone::preferencesDialog() {
	QSettings settings("otter", "dict");
	
	QDialog * dialog = new QDialog();
	
	QPushButton * okButton = new QPushButton("OK", dialog);
	connect(okButton, SIGNAL(clicked()), dialog, SLOT(accept()));
	QPushButton * cancelButton = new QPushButton("Cancel", dialog);
	connect(cancelButton, SIGNAL(clicked()), dialog, SLOT(reject()));
	QBoxLayout * buttonLayout = new QHBoxLayout();
	buttonLayout->addWidget(okButton);
	buttonLayout->addWidget(cancelButton);
	
	QLabel * dictionaryCountLabel = new QLabel("Number of dictionaries", dialog);
	QComboBox * dictionaryCountCombo = new QComboBox(dialog);
	dictionaryCountCombo->addItem("1");
	dictionaryCountCombo->addItem("2");
	dictionaryCountCombo->addItem("3");
	dictionaryCountCombo->addItem("4");
	dictionaryCountCombo->addItem("5");
	dictionaryCountCombo->setCurrentIndex(resultViewers_.size() - 1);
	
	QLabel * pluginDirectoryLabel = new QLabel("Directory with plugins", dialog);
	QLineEdit * pluginDirectory = new QLineEdit(dialog);
	{
		QString directories;
		settings.beginGroup("application");
		int size = settings.beginReadArray("plugindirectory");
		for (int i = 0; i < size; i++) {
			settings.setArrayIndex(i);
			QString dir = settings.value("directory").toString();
			if (dir.isEmpty()) {
				continue;
			}
			directories += dir + ":";
		}
		pluginDirectory->setText(directories);
		settings.endArray();
		settings.endGroup();
	}
	
	
	QLabel * reloadInfoLabel = new QLabel(
		"OtterDict needs to be restarted to apply the changes.", dialog);
	reloadInfoLabel->setWordWrap(true);
	reloadInfoLabel->setFrameShape(QFrame::StyledPanel);
	
	QGridLayout * preferencesLayout = new QGridLayout(dialog);
	preferencesLayout->setSizeConstraint(QLayout::SetFixedSize);
	preferencesLayout->addWidget(dictionaryCountLabel, 0, 0, Qt::AlignRight);
	preferencesLayout->addWidget(dictionaryCountCombo, 0, 1, Qt::AlignLeft);
	preferencesLayout->addWidget(pluginDirectoryLabel, 1, 0, Qt::AlignRight);
	preferencesLayout->addWidget(pluginDirectory, 1, 1, Qt::AlignLeft);
	preferencesLayout->addWidget(reloadInfoLabel, 2, 0, 1, 2, Qt::AlignHCenter);
	preferencesLayout->addLayout(buttonLayout, 3, 0, 1, 2, Qt::AlignHCenter);
	
	dialog->setSizeGripEnabled(false);
	dialog->setWindowTitle("OtterDict preferences");
	
	QDialog::DialogCode retCode = (QDialog::DialogCode)dialog->exec();
	if (retCode == QDialog::Rejected) {
		return;
	}
	
	int dictionaryCount = dictionaryCountCombo->currentIndex() + 1;
	
	settings.setValue("mainwindow/dictionarycount", dictionaryCount);
	
	// Write the application settings.
	settings.beginGroup("application");
	
	// Write the plugin directories.
	{
		settings.beginWriteArray("plugindirectory");
		
		QStringList dirs = pluginDirectory->text().split(":", QString::SkipEmptyParts);
		QStringList::iterator e = dirs.end();
		int idx;
		QStringList::iterator i;
		for (idx = 0, i = dirs.begin(); i != e; ++i, idx++) {
			settings.setArrayIndex(idx);
			settings.setValue("directory", *i);
		}
		
		settings.endArray();
	}
	
	settings.endGroup();
}
Example #5
0
// Запись данных в модель
void ComboBoxMailDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index)const
{


    QComboBox* pRes = dynamic_cast<QComboBox*>(editor);
    if (pRes) {
        if (index.column() == 1) {

            QString pole = index.model()->data(index.sibling(index.row(), 0)).toString();
            int j;
            for (int i = 0; i < fieldName.count(); i++) {
                QString s = this->model->headerData(fieldName.at(i) , Qt::Horizontal).toString();
                s.replace("\n", " ");
                if (s == pole) {
                    j = fieldName.at(i);
                    break;
                }
            }

            if (this->model->data(this->model->index(0, j), Qt::EditRole).type() == QVariant::Bool) {
                model->setData(index, pRes->currentIndex(), Qt::EditRole);
                return;
            }

            QString str = pRes->model()->data(pRes->model()->index(pRes->currentIndex(), 0)).toString();
            model->setData(index, str, Qt::EditRole);

        }
        else {
            QString str = pRes->currentText();
            model->setData(index, str, Qt::EditRole);

            if (index.column() == 0)
                model->setData(index.sibling(index.row(), 1), "", Qt::EditRole);

            // Добавление строки
            bool spaceflag = false;
            for (int i = 0; i < index.model()->rowCount(); i++) {

                QString valstr = index.model()->data(index.sibling(i, 0)).toString();

                if (valstr == tr("")) {
                    spaceflag = true;
                    break;
                }
            }

            if (spaceflag == false) {

                int row = index.model()->rowCount();
                if (row < 0)
                    row = 0;
                model->insertRow(row);
                model->submit();
            }
        }

    }
    else {
        QItemDelegate::setModelData(editor, model, index);
    }
};
void QgsComposerColumnAlignmentDelegate::setModelData( QWidget* editor, QAbstractItemModel* model, const QModelIndex& index ) const
{
  QComboBox *comboBox = static_cast<QComboBox*>( editor );
  Qt::AlignmentFlag alignment = ( Qt::AlignmentFlag ) comboBox->itemData( comboBox->currentIndex() ).toInt();
  model->setData( index, alignment, Qt::EditRole );
}
Example #7
0
/**
 * Replots the currently loaded workspaces.
 */
void DataComparison::plotWorkspaces()
{
  int globalSpecIndex = m_uiForm.sbSpectrum->value();
  int maxGlobalSpecIndex = 0;

  int numRows = m_uiForm.twCurrentData->rowCount();
  for(int row = 0; row < numRows; row++)
  {
    // Get workspace
    QString workspaceName = m_uiForm.twCurrentData->item(row, WORKSPACE_NAME)->text();
    MatrixWorkspace_const_sptr workspace =
      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(workspaceName.toStdString());
    int numSpec = static_cast<int>(workspace->getNumberHistograms());

    // Calculate spectrum number
    QSpinBox *specOffsetSpin = dynamic_cast<QSpinBox *>(m_uiForm.twCurrentData->cellWidget(row, SPEC_OFFSET));
    int specOffset = specOffsetSpin->value();
    int specIndex = globalSpecIndex - specOffset;
    g_log.debug() << "Spectrum index for workspace " << workspaceName.toStdString()
                  << " is " << specIndex << ", with offset " << specOffset << std::endl;

    // See if this workspace extends the reach of the global spectrum selector
    int maxGlobalSpecIndexForWs = numSpec + specOffset - 1;
    if(maxGlobalSpecIndexForWs > maxGlobalSpecIndex)
      maxGlobalSpecIndex = maxGlobalSpecIndexForWs;

    // Check the spectrum index is in range
    if(specIndex >= numSpec || specIndex < 0)
    {
      g_log.debug() << "Workspace " << workspaceName.toStdString()
                    << ", spectrum index out of range." << std::endl;;

      // Give "n/a" in current spectrum display
      m_uiForm.twCurrentData->item(row, CURRENT_SPEC)->setText(tr("n/a"));

      // Detech the curve from the plot
      if(m_curves.contains(workspaceName))
        m_curves[workspaceName]->attach(NULL);

      continue;
    }

    // Update current spectrum display
    m_uiForm.twCurrentData->item(row, CURRENT_SPEC)->setText(tr(QString::number(specIndex)));

    // Create the curve data
    const bool logScale(false), distribution(false);
    QwtWorkspaceSpectrumData wsData(*workspace, static_cast<int>(specIndex), logScale, distribution);

    // Detach the old curve from the plot if it exists
    if(m_curves.contains(workspaceName))
      m_curves[workspaceName]->attach(NULL);

    QComboBox *colourSelector = dynamic_cast<QComboBox *>(m_uiForm.twCurrentData->cellWidget(row, COLOUR));
    QColor curveColour = colourSelector->itemData(colourSelector->currentIndex()).value<QColor>();

    // Create a new curve and attach it to the plot
    boost::shared_ptr<QwtPlotCurve> curve(new QwtPlotCurve);
    curve->setData(wsData);
    curve->setPen(curveColour);
    curve->attach(m_plot);
    m_curves[workspaceName] = curve;
  }

  // Plot the diff
  plotDiffWorkspace();

  // Update the plot
  m_plot->replot();

  // Set the max value for global spectrum spin box
  m_uiForm.sbSpectrum->setMaximum(maxGlobalSpecIndex);
  m_uiForm.sbSpectrum->setSuffix(" / " + QString::number(maxGlobalSpecIndex));
}
//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);
}
bool QgsAttributeEditor::retrieveValue( QWidget *widget, QgsVectorLayer *vl, int idx, QVariant &value )
{
  if ( !widget )
    return false;

  const QgsField &theField = vl->pendingFields()[idx];
  QgsVectorLayer::EditType editType = vl->editType( idx );
  bool modified = false;
  QString text;

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

  QLineEdit *le = qobject_cast<QLineEdit *>( widget );
  if ( le )
  {
    text = le->text();
    modified = le->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QTextEdit *te = qobject_cast<QTextEdit *>( widget );
  if ( te )
  {
    text = te->toHtml();
    modified = te->document()->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QPlainTextEdit *pte = qobject_cast<QPlainTextEdit *>( widget );
  if ( pte )
  {
    text = pte->toPlainText();
    modified = pte->document()->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QComboBox *cb = qobject_cast<QComboBox *>( widget );
  if ( cb )
  {
    if ( editType == QgsVectorLayer::UniqueValues ||
         editType == QgsVectorLayer::ValueMap ||
         editType == QgsVectorLayer::Classification ||
         editType == QgsVectorLayer::ValueRelation )
    {
      text = cb->itemData( cb->currentIndex() ).toString();
      if ( text == nullValue )
      {
        text = QString::null;
      }
    }
    else
    {
      text = cb->currentText();
    }
    modified = true;
  }

  QListWidget *lw = qobject_cast<QListWidget *>( widget );
  if ( lw )
  {
    if ( editType == QgsVectorLayer::ValueRelation )
    {
      text = '{';
      for ( int i = 0, n = 0; i < lw->count(); i++ )
      {
        if ( lw->item( i )->checkState() == Qt::Checked )
        {
          if ( n > 0 )
          {
            text.append( ',' );
          }
          text.append( lw->item( i )->data( Qt::UserRole ).toString() );
          n++;
        }
      }
      text.append( '}' );
    }
    else
    {
      text = QString::null;
    }
    modified = true;
  }

  QSpinBox *sb = qobject_cast<QSpinBox *>( widget );
  if ( sb )
  {
    text = QString::number( sb->value() );
  }

  QAbstractSlider *slider = qobject_cast<QAbstractSlider *>( widget );
  if ( slider )
  {
    text = QString::number( slider->value() );
  }

  QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox *>( widget );
  if ( dsb )
  {
    text = QString::number( dsb->value() );
  }

  QCheckBox *ckb = qobject_cast<QCheckBox *>( widget );
  if ( ckb )
  {
    QPair<QString, QString> states = vl->checkedState( idx );
    text = ckb->isChecked() ? states.first : states.second;
  }

  QCalendarWidget *cw = qobject_cast<QCalendarWidget *>( widget );
  if ( cw )
  {
    text = cw->selectedDate().toString();
  }

  le = widget->findChild<QLineEdit *>();
  if ( le )
  {
    text = le->text();
  }

  switch ( theField.type() )
  {
    case QVariant::Int:
    {
      bool ok;
      int myIntValue = text.toInt( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myIntValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    case QVariant::LongLong:
    {
      bool ok;
      qlonglong myLongValue = text.toLong( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myLongValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    case QVariant::Double:
    {
      bool ok;
      double myDblValue = text.toDouble( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myDblValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    case QVariant::Date:
    {
      QDate myDateValue = QDate::fromString( text, Qt::ISODate );
      if ( myDateValue.isValid() && !text.isEmpty() )
      {
        value = myDateValue;
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    default: //string
      modified = true;
      value = QVariant( text );
      break;
  }

  return modified;
}
Example #10
0
void HadamardOp::operator()(const imagein::Image* img, const std::map<const imagein::Image*, std::string>&) {


    QDialog* dialog = new QDialog(QApplication::activeWindow());
    dialog->setWindowTitle(qApp->translate("Operations", "8x8 transforms"));
    QFormLayout* layout = new QFormLayout(dialog);
    QComboBox* transformBox = new QComboBox(dialog);
    transformBox->addItems(QStringList() << "Hadamard" << "Haar" << "Cosinus (DCT)");
    layout->insertRow(0, qApp->translate("Hadamard", "Transform : "), transformBox);

    QLabel* title = new QLabel(qApp->translate("Transforms", "<b>Select the coefficients to keep : </b>"));
    title->setAlignment(Qt::AlignCenter);
    layout->insertRow(1, title);

    QHBoxLayout* buttonLayout = new QHBoxLayout();
    QPushButton* selectAllButton = new QPushButton(qApp->translate("Transforms", "Clear selection"));
    QPushButton* selectNoneButton = new QPushButton(qApp->translate("Transforms", "Invert selection"));
    buttonLayout->addWidget(selectAllButton);
    buttonLayout->addWidget(selectNoneButton);
    layout->insertRow(2, buttonLayout);

    QWidget* coefWidget = new QWidget(dialog);
    QGridLayout* coefLayout = new QGridLayout(coefWidget);
    QCheckBox* checkBoxes[8][8];
    for(int i = 0; i < 8; ++i) {
        QLabel* labeli = new QLabel(QString("%1").arg(i));
        QLabel* labelj = new QLabel(QString("%1").arg(i));
        labeli->setAlignment(Qt::AlignCenter);
        labelj->setAlignment(Qt::AlignCenter);
        coefLayout->addWidget(labeli, 0, i + 1);
        coefLayout->addWidget(labelj, i + 1, 0);
    }
    for(int j = 0; j < 8; ++j) {
        for(int i = 0; i < 8; ++i) {
            checkBoxes[j][i] = new QCheckBox(coefWidget);
            coefLayout->addWidget(checkBoxes[j][i], j + 1, i + 1);
            checkBoxes[j][i]->setChecked(true);
            QObject::connect(selectAllButton, SIGNAL(clicked(bool)), checkBoxes[j][i], SLOT(setChecked(bool)));
            QObject::connect(selectNoneButton, SIGNAL(clicked()), checkBoxes[j][i], SLOT(toggle()));
        }
    }
    layout->insertRow(3, coefWidget);

    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, Qt::Horizontal, dialog);
    layout->insertRow(4, buttonBox);
    QObject::connect(buttonBox, SIGNAL(accepted()), dialog, SLOT(accept()));
    QObject::connect(buttonBox, SIGNAL(rejected()), dialog, SLOT(reject()));

    QDialog::DialogCode code = static_cast<QDialog::DialogCode>(dialog->exec());


    if(code!=QDialog::Accepted) return;

    GrayscaleImage_t<bool>* selection = new GrayscaleImage_t<bool>(8, 8);
    for(int j = 0; j < 8; ++j) {
        for(int i = 0; i < 8; ++i) {
            selection->setPixelAt(i, j, checkBoxes[j][i]->isChecked());
        }
    }
//    GrayscaleImage* im = Converter<GrayscaleImage>::convert(*img);
    string s;
    Image_t<double> *resImg;
    Image* invImg;
    if(transformBox->currentIndex() == 0) {
        s = Transforms::Hadamard(img, &resImg, &invImg, selection);
        outDoubleImage(resImg, qApp->translate("Transforms", "Hadamard transform").toStdString(), true, true, 256., true);
        outImage(invImg, qApp->translate("Transforms", "Hadamard reconstruction").toStdString());
    }
    else if(transformBox->currentIndex() == 1) {
        s = Transforms::Haar(img, &resImg, &invImg, selection);
        outDoubleImage(resImg, qApp->translate("Transforms", "Haar transform").toStdString(), true, true, 256., true);
        outImage(invImg, qApp->translate("Transforms", "Haar reconstruction").toStdString());
    }
    else if(transformBox->currentIndex() == 2) {
        s = Transforms::cosinus(img, &resImg, &invImg, selection);
        outDoubleImage(resImg, qApp->translate("Transforms", "cosinus transform").toStdString(), true, true, 256., true);
        outImage(invImg, qApp->translate("Transforms", "cosinus reconstruction").toStdString());
    }
    outText(s);
}
Example #11
0
//===========================
void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
  QComboBox *combo = static_cast<QComboBox*>(editor);
  int value = combo->currentIndex();
  model->setData(index, value);
}
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 );
      }
    }
  }
}
void QgsVectorLayerProperties::apply()
{
  //
  // Set up sql subset query if applicable
  //
#ifdef HAVE_POSTGRESQL
  //see if we are dealing with a pg layer here
  if ( layer->providerType() == "postgres" )
  {
    grpSubset->setEnabled( true );
    // set the subset sql for the layer
    layer->setSubsetString( txtSubsetSQL->toPlainText() );
    // update the metadata with the updated sql subset
    QString myStyle = QgsApplication::reportStyleSheet();
    teMetadata->clear();
    teMetadata->document()->setDefaultStyleSheet( myStyle );
    teMetadata->setHtml( metadata() );
    // update the extents of the layer (fetched from the provider)
    layer->updateExtents();
  }
#endif
  // set up the scale based layer visibility stuff....
  layer->toggleScaleBasedVisibility( chkUseScaleDependentRendering->isChecked() );
  layer->setMinimumScale( spinMinimumScale->value() );
  layer->setMaximumScale( spinMaximumScale->value() );

  // update the display field
  layer->setDisplayField( displayFieldComboBox->currentText() );

  actionDialog->apply();

  labelDialog->apply();
  layer->enableLabels( labelCheckBox->isChecked() );
  layer->setLayerName( displayName() );

  for ( int i = 0; i < tblAttributes->rowCount(); i++ )
  {
    int idx = tblAttributes->item( i, 0 )->text().toInt();
    const QgsField &field = layer->pendingFields()[idx];

    QComboBox *cb = dynamic_cast<QComboBox*>( tblAttributes->cellWidget( i, 6 ) );
    if ( !cb )
      continue;

    QgsVectorLayer::EditType editType = ( QgsVectorLayer::EditType ) cb->itemData( cb->currentIndex() ).toInt();
    layer->setEditType( idx, editType );

    QString value = tblAttributes->item( i, 7 ) ? tblAttributes->item( i, 7 )->text() : QString::null;

    if ( editType == QgsVectorLayer::ValueMap )
    {
      QMap<QString, QVariant> &map = layer->valueMap( idx );
      map.clear();

      if ( !value.isEmpty() )
      {
        QStringList values = value.split( ";" );
        for ( int j = 0; j < values.size(); j++ )
        {
          QStringList args = values[j].split( "=" );
          QVariant value;

          if ( args.size() == 1 || ( args.size() == 2 && args[0] == args[1] ) )
          {
            QgsDebugMsg( QString( "idx:%1 key:%2 value:%2" ).arg( idx ).arg( args[0] ) );
            value = args[0];
          }
          else if ( args.size() == 2 )
          {
            QgsDebugMsg( QString( "idx:%1 key:%2 value:%3" ).arg( idx ).arg( args[0] ).arg( args[1] ) );
            value = args[1];

          }

          if ( value.canConvert( field.type() ) )
          {
            map.insert( args[0], value );
          }
        }
      }
    }
    else if ( editType == QgsVectorLayer::EditRange ||
              editType == QgsVectorLayer::SliderRange )
    {
      QStringList values = value.split( ";" );

      if ( values.size() == 3 )
      {
        QVariant min  = values[0];
        QVariant max  = values[1];
        QVariant step = values[2];

        if ( min.canConvert( field.type() ) &&
             max.canConvert( field.type() ) &&
             step.canConvert( field.type() ) )
        {
          min.convert( field.type() );
          max.convert( field.type() );
          step.convert( field.type() );
          layer->range( idx ) = QgsVectorLayer::RangeData( min, max, step );
        }
      }
    }
  }

  QgsSingleSymbolDialog *sdialog =
    dynamic_cast < QgsSingleSymbolDialog * >( widgetStackRenderers->currentWidget() );
  QgsGraduatedSymbolDialog *gdialog =
    dynamic_cast < QgsGraduatedSymbolDialog * >( widgetStackRenderers->currentWidget() );
  QgsContinuousColorDialog *cdialog =
    dynamic_cast < QgsContinuousColorDialog * >( widgetStackRenderers->currentWidget() );
  QgsUniqueValueDialog* udialog =
    dynamic_cast< QgsUniqueValueDialog * >( widgetStackRenderers->currentWidget() );

  if ( sdialog )
  {
    sdialog->apply();
  }
  else if ( gdialog )
  {
    gdialog->apply();
  }
  else if ( cdialog )
  {
    cdialog->apply();
  }
  else if ( udialog )
  {
    udialog->apply();
  }
  layer->setTransparency( static_cast < unsigned int >( 255 - sliderTransparency->value() ) );

  // update symbology
  emit refreshLegend( layer->getLayerID(), false );

  layer->triggerRepaint();
  // notify the project we've made a change
  QgsProject::instance()->dirty( true );

}
Example #14
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 #15
0
void qtractorMidiEventItemDelegate::setModelData ( QWidget *pEditor,
	QAbstractItemModel *pModel,	const QModelIndex& index ) const
{
	const qtractorMidiEventListModel *pListModel
		= static_cast<const qtractorMidiEventListModel *> (pModel);

	qtractorMidiEvent *pEvent = pListModel->eventOfIndex(index);
	if (pEvent == NULL)
		return;

	qtractorMidiEditor *pMidiEditor = pListModel->editor();
	if (pMidiEditor == NULL)
		return;

#ifdef CONFIG_DEBUG
	qDebug("qtractorMidiEventItemDelegate::setModelData(%p, %p, %d, %d)",
		pEditor, pListModel, index.row(), index.column());
#endif

	qtractorTimeScale *pTimeScale = pMidiEditor->timeScale();

	qtractorMidiEditCommand *pEditCommand
		= new qtractorMidiEditCommand(pMidiEditor->midiClip(),
			tr("edit %1").arg(pListModel->headerData(
				index.column(), Qt::Horizontal, Qt::DisplayRole)
					.toString().toLower()));

	switch (index.column()) {
	case 0: // Time.
	{
		qtractorTimeSpinBox *pTimeSpinBox
			= qobject_cast<qtractorTimeSpinBox *> (pEditor);
		if (pTimeSpinBox) {
			unsigned long iTime
				= pTimeScale->tickFromFrame(pTimeSpinBox->valueFromText());
			if (iTime  > pMidiEditor->timeOffset())
				iTime -= pMidiEditor->timeOffset();
			else
				iTime = 0;
			unsigned long iDuration = 0;
			if (pEvent->type() == qtractorMidiEvent::NOTEON)
				iDuration = pEvent->duration();
			pEditCommand->resizeEventTime(pEvent, iTime, iDuration);
		}
		break;
	}

	case 2: // Name.
	{
		QComboBox *pComboBox = qobject_cast<QComboBox *> (pEditor);
		if (pComboBox) {
			const int iNote = pComboBox->currentIndex();
			const unsigned long iTime = pEvent->time();
			pEditCommand->moveEvent(pEvent, iNote, iTime);
		}
		break;
	}

	case 3: // Value.
	{
		QSpinBox *pSpinBox = qobject_cast<QSpinBox *> (pEditor);
		if (pSpinBox) {
			const int iValue = pSpinBox->value();
			pEditCommand->resizeEventValue(pEvent, iValue);
		}
		break;
	}

	case 4: // Duration/Data.
	{
		qtractorTimeSpinBox *pTimeSpinBox
			= qobject_cast<qtractorTimeSpinBox *> (pEditor);
		if (pTimeSpinBox) {
			const unsigned long iTime = pEvent->time();
			const unsigned long iDuration
				= pTimeScale->tickFromFrame(pTimeSpinBox->value());
			pEditCommand->resizeEventTime(pEvent, iTime, iDuration);
		}
		break;
	}

	default:
		break;
	}

	// Do it.
	pMidiEditor->commands()->exec(pEditCommand);
}
Example #16
0
int drv_combobox(int drvid, void *a0, void* a1, void* a2, void* a3, void* a4, void* a5, void* a6, void* a7, void* a8, void* a9)
{
    handle_head* head = (handle_head*)a0;
    QComboBox *self = (QComboBox*)head->native;
    switch (drvid) {
    case COMBOBOX_INIT: {
        drvNewObj(a0,new QComboBox);
        break;
    }
    case COMBOBOX_COUNT: {
        drvSetInt(a1,self->count());
        break;
    }
    case COMBOBOX_SETCURRENTINDEX: {
        self->setCurrentIndex(drvGetInt(a1));
        break;
    }
    case COMBOBOX_CURRENTINDEX: {
        drvSetInt(a1,self->currentIndex());
        break;
    }
    case COMBOBOX_CURRENTTEXT: {
        drvSetString(a1,self->currentText());
        break;
    }
    case COMBOBOX_SETEDITABLE: {
        self->setEditable(drvGetBool(a1));
        break;
    }
    case COMBOBOX_ISEDITABLE: {
        drvSetBool(a1,self->isEditable());
        break;
    }
    case COMBOBOX_SETMAXCOUNT: {
        self->setMaxCount(drvGetInt(a1));
        break;
    }
    case COMBOBOX_MAXCOUNT: {
        drvSetInt(a1,self->maxCount());
        break;
    }
    case COMBOBOX_SETMAXVISIBLEITEMS: {
        self->setMaxVisibleItems(drvGetInt(a1));
        break;
    }
    case COMBOBOX_MAXVISIBLEITEMS: {
        drvSetInt(a1,self->maxVisibleItems());
        break;
    }
    case COMBOBOX_SETMINIMUMCONTENTSLENGTH: {
        self->setMinimumContentsLength(drvGetInt(a1));
        break;
    }
    case COMBOBOX_MINIMUNCONTENTSLENGHT: {
        drvSetInt(a1,self->minimumContentsLength());
        break;
    }
    case COMBOBOX_ADDITEM: {
        self->addItem(drvGetString(a1));
        break;
    }
    case COMBOBOX_INSERTITEM: {
        self->insertItem(drvGetInt(a1),drvGetString(a2));
        break;
    }
    case COMBOBOX_REMOVEITEM: {
        self->removeItem(drvGetInt(a1));
        break;
    }
    case COMBOBOX_ITEMTEXT: {
        drvSetString(a2,self->itemText(drvGetInt(a1)));
        break;
    }
    case COMBOBOX_ONCURRENTINDEXCHANGED: {
        QObject::connect(self,SIGNAL(currentIndexChanged(int)),drvNewSignal(self,a1,a2),SLOT(call(int)));
        break;
    }
    default:
        return 0;
    }
    return 1;
}
Example #17
0
QByteArray TableItem::GenHTMLForm() {
    QString ret;
    QString objTypeName = obj->metaObject()->className();

    if(objTypeName == "QPlainTextEdit") {
        QPlainTextEdit *item = (QPlainTextEdit *) obj;

#if 0
        ret = QString("<form method=\"post\">"
                   "  <input type=\"hidden\" name=\"action\" value=\"%2\">"
                   "<div class=\"form_info\">%1</div>"
                   "<div class=\"form_editor\"><textarea name=\"%2\" cols=\"20\" rows=\"4\">%3</textarea></div>"
                   "<div class=\"form_submitter\"><input type=\"submit\" value=\"&gt;&gt;\"></div>"
                   "<div class=\"form_tooltip\">%4</div>"
                   "</form>")
                .arg(desc).arg(short_d).arg(item->toPlainText()).arg(item->toolTip());
#endif
        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                      "<div class=\"prop\"><p>%1:</p></div>"
                      "<div class=\"val\"><p><textarea name=\"%2\" cols=\"16\" rows=\"3\">%3</textarea></p></div>"
                      "<div class=\"submit\"><p> %4</p></div>"
                      "<div class=\"tooltip\"><p> %5</p></div>"
                      "</div></form>\n")
                .arg(desc)
                .arg(short_d)
                .arg(item->toPlainText())
                .arg((!item->isEnabled() || item->isReadOnly()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                .arg(item->toolTip());
    }
    else if(objTypeName == "QLineEdit") {
        QLineEdit *item = (QLineEdit *) obj;

        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                        "<div class=\"prop\"><p>%1:</p></div>"
                        "<div class=\"val\"><p><input type=\"text\" name=\"%2\" value=\"%3\" /></p></div>"
                        "<div class=\"submit\"><p> %4</p></div>"
                        "<div class=\"tooltip\"><p> %5</p></div>"
                        "</div></form>\n")
                .arg(desc)
                .arg(short_d)
                .arg(item->text())
                .arg((!item->isEnabled() || item->isReadOnly()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                .arg(item->toolTip());
    }
    else if(objTypeName == "QCheckBox") {
        QCheckBox *item = (QCheckBox *) obj;
        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                        "<div class=\"prop\"><p>%1:</p></div>"
                        "<div class=\"val\"><p><input type=\"checkbox\" name=\"%2\" value=\"true\" %3/></p></div>"
                        "<div class=\"submit\"><p> %4</p></div>"
                        "<div class=\"tooltip\"><p> %5</p></div>"
                        "</div></form>\n")
                .arg(desc)
                .arg(short_d)
                .arg(item->isChecked() ? "checked" : "")
                .arg((!item->isEnabled()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                .arg(item->toolTip());
    }
    else if(objTypeName == "QSpinBox") {
        QSpinBox *item = (QSpinBox *) obj;

        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                        "<div class=\"prop\"><p>%1:</p></div>"
                        "<div class=\"val\"><p><input type=\"number\" name=\"%2\" value=\"%3\" min=\"%4\" max=\"%5\" step=\"%6\" /></p></div>"
                        "<div class=\"submit\"><p> %7</p></div>"
                        "<div class=\"tooltip\"><p> %8</p></div>"
                        "</div></form>\n")
                .arg(desc)
                .arg(short_d)
                .arg(item->value())
                .arg(item->minimum())
                .arg(item->maximum())
                .arg(item->singleStep())
                .arg((!item->isEnabled() || item->isReadOnly()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                .arg(item->toolTip());
    }
    else if(objTypeName == "QDoubleSpinBox") {
        QDoubleSpinBox *item = (QDoubleSpinBox *) obj;

        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                        "<div class=\"prop\"><p>%1:</p></div>"
                        "<div class=\"val\"><p><input type=\"number\" name=\"%2\" value=\"%3\" min=\"%4\" max=\"%5\" step=\"%6\" /></p></div>"
                        "<div class=\"submit\"><p> %7</p></div>"
                        "<div class=\"tooltip\"><p> %8</p></div>"
                        "</div></form>\n")
                .arg(desc)
                .arg(short_d)
                .arg(item->value())
                .arg(item->minimum())
                .arg(item->maximum())
                .arg(item->singleStep())
                .arg((!item->isEnabled() || item->isReadOnly()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                .arg(item->toolTip());
    }
    else if(objTypeName == "QComboBox") {
        QComboBox *item = (QComboBox *) obj;

        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                        "<div class=\"prop\"><p>%1:</p></div>"
                        "<div class=\"val\"><p>\n<select name=\"%2\" style=\"max-width:170px;\">\n").arg(desc).arg(short_d);
                      int current = item->currentIndex();
                      for (int i = 0; i < item->count(); i++) {
                          ret.append(QString("<option value=\"%1\" %2>%3</option>\n").arg(i).arg(i==current ? "selected" : "").arg(item->itemText(i)));
                      }

                      ret.append(QString("</select>\n</p></div>"
                        "<div class=\"submit\"><p> %1</p></div>"
                        "<div class=\"tooltip\"><p> %2</p></div>"
                        "</div></form>\n")
                        .arg((!item->isEnabled()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                        .arg(item->toolTip()));

    }
    else if(objTypeName == "QRadioButton") {
        QRadioButton *item = (QRadioButton *) obj;

        QString rb_vals;

        if(item->objectName() == "radioButton_rds_music") {
            rb_vals = QString("<input type=\"radio\" name=\"%1\" value=\"true\" %2/> Music <input type=\"radio\" name=\"%1\" value=\"false\" %3/> Speech")
                .arg(short_d).arg(item->isChecked() ? "checked" : "").arg(item->isChecked() ? "" : "checked");
        }

        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                        "<div class=\"prop\"><p>%1:</p></div>"
                        "<div class=\"val\"><p>%3</p></div>"
                        "<div class=\"submit\"><p> %4</p></div>"
                        "<div class=\"tooltip\"><p> %5</p></div>"
                        "</div></form>\n")
                .arg(desc)
                .arg(short_d)
                .arg(rb_vals)
                .arg((!item->isEnabled()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                .arg(item->toolTip());
    }
    else if(objTypeName == "QPushButton") {
        QPushButton *item = (QPushButton *) obj;

        ret = QString("<form method=\"post\"><input type=\"hidden\" name=\"action\" value=\"%2\" />"
                      "<div class=\"row\">"
                        "<div class=\"prop\"><p>%1:</p></div>"
                        "<div class=\"val\"><p>%3</p></div>"
                        "<div class=\"submit\"><p> %4</p></div>"
                        "<div class=\"tooltip\"><p> %5</p></div>"
                        "</div></form>\n")
                .arg(desc)
                .arg(short_d)
                .arg("action")
                .arg((!item->isEnabled()) ? "" : "<input type=\"submit\" value=\"&gt;&gt;\" />")
                .arg(item->toolTip());
    }
    else {
        qDebug() << "unimplemented obj_type: " << objTypeName;
    }

    return ret.toUtf8();
};
 virtual void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const {
     QComboBox* ed = static_cast<QComboBox*>(editor);
     model->setData(index, ed->itemData(ed->currentIndex()));
 }
Example #19
0
void EditStyle::getValues()
      {
      lstyle.set(ST_staffUpperBorder,        Spatium(staffUpperBorder->value()));
      lstyle.set(ST_staffLowerBorder,        Spatium(staffLowerBorder->value()));
      lstyle.set(ST_staffDistance,           Spatium(staffDistance->value()));
      lstyle.set(ST_akkoladeDistance,        Spatium(akkoladeDistance->value()));
      lstyle.set(ST_minSystemDistance,       Spatium(minSystemDistance->value()));
      lstyle.set(ST_maxSystemDistance,       Spatium(maxSystemDistance->value()));
      lstyle.set(ST_lyricsDistance,          Spatium(lyricsDistance->value()));
      lstyle.set(ST_lyricsMinBottomDistance, Spatium(lyricsMinBottomDistance->value()));
      lstyle.set(ST_lyricsLineHeight,        Spatium(lyricsLineHeight->value() * .01));
      lstyle.set(ST_systemFrameDistance,     Spatium(systemFrameDistance->value()));
      lstyle.set(ST_frameSystemDistance,     Spatium(frameSystemDistance->value()));
      lstyle.set(ST_minMeasureWidth,         Spatium(minMeasureWidth_2->value()));

      lstyle.set(ST_barWidth,                Spatium(barWidth->value()));
      lstyle.set(ST_endBarWidth,             Spatium(endBarWidth->value()));
      lstyle.set(ST_endBarDistance,          Spatium(endBarDistance->value()));
      lstyle.set(ST_doubleBarWidth,          Spatium(doubleBarWidth->value()));
      lstyle.set(ST_doubleBarDistance,       Spatium(doubleBarDistance->value()));

      lstyle.set(ST_repeatBarTips,           showRepeatBarTips->isChecked());
      lstyle.set(ST_startBarlineSingle,      showStartBarlineSingle->isChecked());
      lstyle.set(ST_startBarlineMultiple,    showStartBarlineMultiple->isChecked());

      lstyle.set(ST_measureSpacing,          measureSpacing->value());
      lstyle.set(ST_minNoteDistance,         Spatium(minNoteDistance->value()));
      lstyle.set(ST_barNoteDistance,         Spatium(barNoteDistance->value()));
      lstyle.set(ST_noteBarDistance,         Spatium(noteBarDistance->value()));
      lstyle.set(ST_showMeasureNumber,       showMeasureNumber->isChecked());
      lstyle.set(ST_showMeasureNumberOne,    showFirstMeasureNumber->isChecked());
      lstyle.set(ST_measureNumberInterval,   intervalMeasureNumber->value());
      lstyle.set(ST_measureNumberSystem,     showEverySystemMeasureNumber->isChecked());
      lstyle.set(ST_measureNumberAllStaffs,  showAllStaffsMeasureNumber->isChecked());
      lstyle.set(ST_clefLeftMargin,          Spatium(clefLeftMargin->value()));
      lstyle.set(ST_keysigLeftMargin,        Spatium(keysigLeftMargin->value()));
      lstyle.set(ST_timesigLeftMargin,       Spatium(timesigLeftMargin->value()));
      lstyle.set(ST_clefKeyRightMargin,      Spatium(clefKeyRightMargin->value()));
      lstyle.set(ST_clefBarlineDistance,     Spatium(clefBarlineDistance->value()));
      lstyle.set(ST_staffLineWidth,          Spatium(staffLineWidth->value()));
      lstyle.set(ST_beamWidth,               Spatium(beamWidth->value()));
      lstyle.set(ST_beamDistance,            beamDistance->value());
      lstyle.set(ST_beamMinLen,              Spatium(beamMinLen->value()));
      lstyle.set(ST_beamMinSlope,            beamMinSlope->value());
      lstyle.set(ST_beamMaxSlope,            beamMaxSlope->value());
      lstyle.set(ST_graceNoteMag,            graceNoteSize->value() * 0.01);
      lstyle.set(ST_smallStaffMag,           smallStaffSize->value() * 0.01);
      lstyle.set(ST_smallNoteMag,            smallNoteSize->value() * 0.01);
      lstyle.set(ST_smallClefMag,            smallClefSize->value() * 0.01);
      lstyle.set(ST_lastSystemFillLimit,     lastSystemFillThreshold->value() * 0.01);
      lstyle.set(ST_hairpinY,                Spatium(hairpinY->value()));
      lstyle.set(ST_hairpinWidth,            Spatium(hairpinLineWidth->value()));
      lstyle.set(ST_hairpinHeight,           Spatium(hairpinHeight->value()));
      lstyle.set(ST_hairpinContHeight,       Spatium(hairpinContinueHeight->value()));
      lstyle.set(ST_genClef,                 genClef->isChecked());
      lstyle.set(ST_genKeysig,               genKeysig->isChecked());
      lstyle.set(ST_genTimesig,              genTimesig->isChecked());
      lstyle.set(ST_genCourtesyTimesig,      genCourtesyTimesig->isChecked());
      lstyle.set(ST_genCourtesyKeysig,       genCourtesyKeysig->isChecked());
      lstyle.set(ST_genCourtesyClef,         genCourtesyClef->isChecked());

      lstyle.set(ST_useGermanNoteNames,      useGermanNoteNames->isChecked());

      if (lstyle.valueSt(ST_chordDescriptionFile) != chordDescriptionFile->text()) {
            ChordList* cl = new ChordList();
            cl->read("chords.xml");
            cl->read(chordDescriptionFile->text());
            lstyle.setChordList(cl);
            lstyle.set(ST_chordDescriptionFile, chordDescriptionFile->text());
            }

      lstyle.set(ST_concertPitch,            concertPitch->isChecked());
      lstyle.set(ST_createMultiMeasureRests, multiMeasureRests->isChecked());
      lstyle.set(ST_minEmptyMeasures,        minEmptyMeasures->value());
      lstyle.set(ST_minMMRestWidth,          Spatium(minMeasureWidth->value()));
      lstyle.set(ST_hideEmptyStaves,         hideEmptyStaves->isChecked());
      lstyle.set(ST_dontHideStavesInFirstSystem, dontHideStavesInFirstSystem->isChecked());

      lstyle.set(ST_accidentalNoteDistance,  Spatium(accidentalNoteDistance->value()));
      lstyle.set(ST_accidentalDistance,      Spatium(accidentalDistance->value()));
      lstyle.set(ST_dotNoteDistance,         Spatium(noteDotDistance->value()));
      lstyle.set(ST_dotDotDistance,          Spatium(dotDotDistance->value()));
      lstyle.set(ST_stemWidth,               Spatium(stemWidth->value()));
      lstyle.set(ST_ledgerLineWidth,         Spatium(ledgerLineWidth->value()));
      lstyle.set(ST_ledgerLineLength,        Spatium(ledgerLineLength->value()));

      lstyle.set(ST_bracketWidth,            Spatium(bracketWidth->value()));
      lstyle.set(ST_bracketDistance,         Spatium(bracketDistance->value()));
      lstyle.set(ST_akkoladeWidth,           Spatium(akkoladeWidth->value()));
      lstyle.set(ST_akkoladeBarDistance,     Spatium(akkoladeBarDistance->value()));

      lstyle.set(ST_propertyDistanceHead,    Spatium(propertyDistanceHead->value()));
      lstyle.set(ST_propertyDistanceStem,    Spatium(propertyDistanceStem->value()));
      lstyle.set(ST_propertyDistance,        Spatium(propertyDistance->value()));
      lstyle.set(ST_stemDir1,                voice1Up->isChecked() ? MScore::UP : MScore::DOWN);
      lstyle.set(ST_stemDir2,                voice2Up->isChecked() ? MScore::UP : MScore::DOWN);
      lstyle.set(ST_stemDir3,                voice3Up->isChecked() ? MScore::UP : MScore::DOWN);
      lstyle.set(ST_stemDir4,                voice4Up->isChecked() ? MScore::UP : MScore::DOWN);

      lstyle.set(ST_shortenStem,             shortenStem->isChecked());
      lstyle.set(ST_shortStemProgression,    Spatium(shortStemProgression->value()));
      lstyle.set(ST_shortestStem,            Spatium(shortestStem->value()));

      lstyle.set(ST_ArpeggioNoteDistance,    Spatium(arpeggioNoteDistance->value()));
      lstyle.set(ST_ArpeggioLineWidth,       Spatium(arpeggioLineWidth->value()));
      lstyle.set(ST_ArpeggioHookLen,         Spatium(arpeggioHookLen->value()));

      lstyle.set(ST_FixMeasureNumbers,       fixNumberMeasures->value());
      lstyle.set(ST_FixMeasureWidth,         fixMeasureWidth->isChecked());

      lstyle.set(ST_SlurEndWidth,            Spatium(slurEndLineWidth->value()));
      lstyle.set(ST_SlurMidWidth,            Spatium(slurMidLineWidth->value()));
      lstyle.set(ST_SlurDottedWidth,         Spatium(slurDottedLineWidth->value()));
      lstyle.set(ST_SlurBow,                 Spatium(slurBow->value()));

      lstyle.set(ST_MusicalSymbolFont,       musicalSymbolFont->currentText());

      lstyle.set(ST_showHeader,      showHeader->isChecked());
      lstyle.set(ST_headerStyled,    headerStyled->isChecked());
      lstyle.set(ST_headerFirstPage, showHeaderFirstPage->isChecked());
      lstyle.set(ST_headerOddEven,   headerOddEven->isChecked());
      if (headerStyled->isChecked()) {
            lstyle.set(ST_evenHeaderL, evenHeaderL->toPlainText());
            lstyle.set(ST_evenHeaderC, evenHeaderC->toPlainText());
            lstyle.set(ST_evenHeaderR, evenHeaderR->toPlainText());
            lstyle.set(ST_oddHeaderL,  oddHeaderL->toPlainText());
            lstyle.set(ST_oddHeaderC,  oddHeaderC->toPlainText());
            lstyle.set(ST_oddHeaderR,  oddHeaderR->toPlainText());
            }
      else {
            lstyle.set(ST_evenHeaderL, evenHeaderL->toHtml());
            lstyle.set(ST_evenHeaderC, evenHeaderC->toHtml());
            lstyle.set(ST_evenHeaderR, evenHeaderR->toHtml());
            lstyle.set(ST_oddHeaderL,  oddHeaderL->toHtml());
            lstyle.set(ST_oddHeaderC,  oddHeaderC->toHtml());
            lstyle.set(ST_oddHeaderR,  oddHeaderR->toHtml());
            }

      lstyle.set(ST_showFooter,      showFooter->isChecked());
      lstyle.set(ST_footerStyled,    footerStyled->isChecked());
      lstyle.set(ST_footerFirstPage, showFooterFirstPage->isChecked());
      lstyle.set(ST_footerOddEven,   footerOddEven->isChecked());
      if (footerStyled->isChecked()) {
            lstyle.set(ST_evenFooterL, evenFooterL->toPlainText());
            lstyle.set(ST_evenFooterC, evenFooterC->toPlainText());
            lstyle.set(ST_evenFooterR, evenFooterR->toPlainText());
            lstyle.set(ST_oddFooterL,  oddFooterL->toPlainText());
            lstyle.set(ST_oddFooterC,  oddFooterC->toPlainText());
            lstyle.set(ST_oddFooterR,  oddFooterR->toPlainText());
            }
      else {
            lstyle.set(ST_evenFooterL, evenFooterL->toHtml());
            lstyle.set(ST_evenFooterC, evenFooterC->toHtml());
            lstyle.set(ST_evenFooterR, evenFooterR->toHtml());
            lstyle.set(ST_oddFooterL,  oddFooterL->toHtml());
            lstyle.set(ST_oddFooterC,  oddFooterC->toHtml());
            lstyle.set(ST_oddFooterR,  oddFooterR->toHtml());
            }

      // figured bass
      int         idx = comboFBFont->currentIndex();
      QString     family;
      if(FiguredBass::fontData(idx, &family, 0, 0, 0))
            lstyle.set(ST_figuredBassFontFamily, family);
      qreal size = doubleSpinFBSize->value();
      qreal vPos = doubleSpinFBVertPos->value();
      lstyle.set(ST_figuredBassFontSize,   size);
      lstyle.set(ST_figuredBassYOffset,    vPos);
      lstyle.set(ST_figuredBassLineHeight, ((double)spinFBLineHeight->value()) / 100.0);
      lstyle.set(ST_figuredBassAlignment,  radioFBTop->isChecked() ? 0 : 1);
      lstyle.set(ST_figuredBassStyle,      radioFBModern->isChecked() ? 0 : 1);
      // copy to text style data relevant to it (LineHeight and Style are not in text style);
      // offsetType is necessarily OFFSET_SPATIUM
      const TextStyle fbOld = lstyle.textStyle(TEXT_STYLE_FIGURED_BASS);
      if(family != fbOld.family() || size != fbOld.size()
                  || vPos != fbOld.offset().y() || fbOld.offsetType() != OFFSET_SPATIUM) {
            TextStyle fbNew(fbOld);
            fbNew.setFamily(family);
            fbNew.setSize(size);
            fbNew.setYoff(vPos);
            fbNew.setOffsetType(OFFSET_SPATIUM);
            lstyle.setTextStyle(fbNew);
      }

      for (int i = 0; i < ARTICULATIONS; ++i) {
            QComboBox* cb = static_cast<QComboBox*>(articulationTable->cellWidget(i, 1));
            lstyle.setArticulationAnchor(i, ArticulationAnchor(cb->itemData(cb->currentIndex()).toInt()));
            }

//      lstyle.set(ST_warnPitchRange,  warnPitchRange->isChecked());

      lstyle.set(ST_voltaY,                  Spatium(voltaY->value()));
      lstyle.set(ST_voltaHook,               Spatium(voltaHook->value()));
      lstyle.set(ST_voltaLineWidth,          Spatium(voltaLineWidth->value()));

      lstyle.set(ST_ottavaY,                 Spatium(ottavaY->value()));
      lstyle.set(ST_ottavaHook,              Spatium(ottavaHook->value()));
      lstyle.set(ST_ottavaLineWidth,         Spatium(ottavaLineWidth->value()));

      lstyle.set(ST_pedalY,                  Spatium(pedalY->value()));
      lstyle.set(ST_trillY,                  Spatium(trillY->value()));
      lstyle.set(ST_harmonyY,                Spatium(harmonyY->value()));
      lstyle.set(ST_harmonyFretDist,         Spatium(harmonyFretDist->value()));
      lstyle.set(ST_minHarmonyDistance,      Spatium(minHarmonyDistance->value()));

      lstyle.set(ST_tabClef, clefTab1->isChecked() ? CLEF_TAB : CLEF_TAB2);
      }
void synthv1widget_controls_item_delegate::setModelData ( QWidget *pEditor,
	QAbstractItemModel *pModel,	const QModelIndex& index ) const
{
#ifdef CONFIG_DEBUG_0
	qDebug("synthv1widget_controls_item_delegate::setModelData(%p, %d, %d)",
		pEditor, index.row(), index.column());
#endif

	switch (index.column()) {
	case 0: // Channel.
	{
		QSpinBox *pSpinBox = qobject_cast<QSpinBox *> (pEditor);
		if (pSpinBox) {
			const int iChannel = pSpinBox->value();
			const QString& sText
				= (iChannel > 0 ? QString::number(iChannel) : tr("Auto"));
			pModel->setData(index, sText);
		}
		break;
	}

	case 1: // Type.
	{
		QComboBox *pComboBox = qobject_cast<QComboBox *> (pEditor);
		if (pComboBox) {
			const QString& sType = pComboBox->currentText();
			pModel->setData(index, sType);
		}
		break;
	}

	case 2: // Parameter.
	{
		QComboBox *pComboBox = qobject_cast<QComboBox *> (pEditor);
		if (pComboBox) {
			const int iIndex = pComboBox->currentIndex();
			QString sText;
			int iParam;
			if (iIndex >= 0) {
				sText = pComboBox->itemText(iIndex);
				iParam = pComboBox->itemData(iIndex).toInt();
			} else {
				sText = pComboBox->currentText();
				iParam = sText.toInt();
			}
			pModel->setData(index, sText);
			pModel->setData(index, iParam, Qt::UserRole);
		}
		break;
	}

	case 3: // Subject.
	{
		QComboBox *pComboBox = qobject_cast<QComboBox *> (pEditor);
		if (pComboBox) {
			const int iIndex = pComboBox->currentIndex();
			pModel->setData(index,
				synthv1_param::paramName(synthv1::ParamIndex(iIndex)));
			pModel->setData(index, iIndex, Qt::UserRole);
		}
		break;
	}

	default:
		break;
	}

	// Done.
}
void ParametersToolBox::updateParametersVisibility()
{
	//show/hide not used parameters
	QComboBox * descriptorBox = this->findChild<QComboBox*>(Settings::kFeature2D_2Descriptor());
	QComboBox * detectorBox = this->findChild<QComboBox*>(Settings::kFeature2D_1Detector());
	if(descriptorBox && detectorBox)
	{
		QString group = Settings::kFeature2D_2Descriptor().split('/').first();
		QWidget * panel = 0;
		for(int i=0; i<this->count(); ++i)
		{
			if(this->widget(i)->objectName().compare(group) == 0)
			{
				panel = this->widget(i);
				break;
			}
		}
		if(panel)
		{
			const QObjectList & objects = panel->children();
			QString descriptorName = descriptorBox->currentText();
			QString detectorName = detectorBox->currentText();

			for(int i=0; i<objects.size(); ++i)
			{
				if(!objects[i]->objectName().isEmpty())
				{
					if(objects[i]->objectName().contains(descriptorName) || objects[i]->objectName().contains(detectorName))
					{
						((QWidget*)objects[i])->setVisible(true);
					}
					else if(objects[i]->objectName().contains("Fast") && detectorName == QString("ORB"))
					{
						((QWidget*)objects[i])->setVisible(true);	// ORB uses some FAST parameters
					}
					else if(!objects[i]->objectName().split('/').at(1).at(0).isDigit())
					{
						((QWidget*)objects[i])->setVisible(false);
					}
				}
			}
		}
	}

	QComboBox * nnBox = this->findChild<QComboBox*>(Settings::kNearestNeighbor_1Strategy());
	if(nnBox)
	{
		QString group = Settings::kNearestNeighbor_1Strategy().split('/').first();
		QWidget * panel = 0;
		for(int i=0; i<this->count(); ++i)
		{
			if(this->widget(i)->objectName().compare(group) == 0)
			{
				panel = this->widget(i);
				break;
			}
		}
		if(panel)
		{
			const QObjectList & objects = panel->children();
			QString nnName = nnBox->currentText();

			for(int i=0; i<objects.size(); ++i)
			{
				if(!objects[i]->objectName().isEmpty())
				{
					if(objects[i]->objectName().contains(nnName))
					{
						((QWidget*)objects[i])->setVisible(true);
					}
					else if(!objects[i]->objectName().split('/').at(1).at(0).isDigit())
					{
						((QWidget*)objects[i])->setVisible(false);
						if(nnBox->currentIndex() < 6 && objects[i]->objectName().split('/').at(1).contains("search"))
						{
							//show flann search parameters
							((QWidget*)objects[i])->setVisible(true);
						}
					}
					else if(objects[i]->objectName().split('/').at(1).contains("Distance_type"))
					{
						// don't show distance when bruteforce is selected
						((QWidget*)objects[i])->setVisible(nnBox->currentIndex() != 6);
					}
				}
			}
		}
	}
}
void RegisterConnDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *cb = qobject_cast<QComboBox *>(editor);
    Q_ASSERT(cb);
    model->setData(index, cb->currentIndex(), Qt::EditRole);
}
Example #23
0
void MainWindow::on_action_Get_samples_triggered()
{
	uint64_t samplerate;
	QString s;
	GSList *devs = NULL;
	int opt_dev;
	struct sr_dev *dev;
	QComboBox *n = ui->comboBoxNumSamples;

	opt_dev = 0; /* FIXME */

	/*
	 * The number of samples to get is a drop-down list, but you can also
	 * manually enter a value. If the latter, we have to get the value from
	 * the lineEdit object, otherwise via itemData() and the list index.
	 */
	if (n->lineEdit() != NULL) {
		limit_samples = n->lineEdit()->text().toLongLong();
	} else {
		limit_samples = n->itemData(n->currentIndex()).toLongLong();
	}

	samplerate = ui->comboBoxSampleRate->itemData(
		ui->comboBoxSampleRate->currentIndex()).toLongLong();

	/* TODO: Sanity checks. */

	/* TODO: Assumes unitsize == 1. */
	if (!(sample_buffer = (uint8_t *)malloc(limit_samples))) {
		/* TODO: Error handling. */
		return;
	}

	sr_session_new();
	sr_session_datafeed_callback_add(datafeed_in);

	devs = sr_dev_list();

	dev = (struct sr_dev *)g_slist_nth_data(devs, opt_dev);

	/* Set the number of samples we want to get from the device. */
	if (dev->driver->dev_config_set(dev->driver_index,
	    SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
		qDebug("Failed to set sample limit.");
		sr_session_destroy();
		return;
	}

	if (sr_session_dev_add(dev) != SR_OK) {
		qDebug("Failed to use device.");
		sr_session_destroy();
		return;
	}

	/* Set the samplerate. */
	if (dev->driver->dev_config_set(dev->driver_index,
	    SR_HWCAP_SAMPLERATE, &samplerate) != SR_OK) {
		qDebug("Failed to set samplerate.");
		sr_session_destroy();
		return;
	};

	if (dev->driver->dev_config_set(dev->driver_index,
	    SR_HWCAP_PROBECONFIG, (char *)dev->probes) != SR_OK) {
		qDebug("Failed to configure probes.");
		sr_session_destroy();
		return;
	}

	if (sr_session_start() != SR_OK) {
		qDebug("Failed to start session.");
		sr_session_destroy();
		return;
	}

	progress = new QProgressDialog("Getting samples from logic analyzer...",
				       "Abort", 0, limit_samples, this);
	progress->setWindowModality(Qt::WindowModal);
	progress->setMinimumDuration(100);

	sr_session_run();

	sr_session_stop();
	sr_session_destroy();

	for (int i = 0; i < getNumChannels(); ++i) {
		channelForms[i]->setNumSamples(limit_samples);
		// channelForms[i]->setSampleStart(0);
		// channelForms[i]->setSampleEnd(limit_samples);

		/* If any of the scale factors change, update all of them.. */
		connect(channelForms[i], SIGNAL(scaleFactorChanged(float)),
		        w, SLOT(updateScaleFactors(float)));

		channelForms[i]->generatePainterPath();
		// channelForms[i]->update();
	}

	setNumSamples(limit_samples);
	
	/* Enable the relevant labels/buttons. */
	ui->labelSampleStart->setEnabled(true);
	ui->labelSampleEnd->setEnabled(true);
	ui->labelScaleFactor->setEnabled(true);
	ui->action_Save_as->setEnabled(true);

	// sr_hw_get_samples_shutdown(&ctx, 1000);
}
void QgsRelationReferenceWidget::filterChanged()
{
  QVariant nullValue = QgsApplication::nullRepresentation();

  QMap<QString, QString> filters;
  QgsAttributeList attrs;

  QComboBox *scb = qobject_cast<QComboBox *>( sender() );

  Q_ASSERT( scb );

  QgsFeature f;
  QgsFeatureIds featureIds;
  QString filterExpression;

  // comboboxes have to be disabled before building filters
  if ( mChainFilters )
    disableChainedComboBoxes( scb );

  // build filters
  const auto constMFilterComboBoxes = mFilterComboBoxes;
  for ( QComboBox *cb : constMFilterComboBoxes )
  {
    if ( cb->currentIndex() != 0 )
    {
      const QString fieldName = cb->property( "Field" ).toString();

      if ( cb->currentText() == nullValue.toString() )
      {
        filters[fieldName] = QStringLiteral( "\"%1\" IS NULL" ).arg( fieldName );
      }
      else
      {
        filters[fieldName] = QgsExpression::createFieldEqualityExpression( fieldName, cb->currentText() );
      }
      attrs << mReferencedLayer->fields().lookupField( fieldName );
    }
  }

  if ( mChainFilters )
  {
    QComboBox *ccb = nullptr;
    const auto constMFilterComboBoxes = mFilterComboBoxes;
    for ( QComboBox *cb : constMFilterComboBoxes )
    {
      if ( !ccb )
      {
        if ( cb == scb )
          ccb = cb;

        continue;
      }

      if ( ccb->currentIndex() != 0 )
      {
        const QString fieldName = cb->property( "Field" ).toString();

        cb->blockSignals( true );
        cb->clear();
        cb->addItem( cb->property( "FieldAlias" ).toString() );

        // ccb = scb
        // cb = scb + 1
        QStringList texts;
        const auto txts { mFilterCache[ccb->property( "Field" ).toString()][ccb->currentText()] };
        for ( const QString &txt : txts )
        {
          QMap<QString, QString> filtersAttrs = filters;
          filtersAttrs[fieldName] = QgsExpression::createFieldEqualityExpression( fieldName, txt );
          QString expression = filtersAttrs.values().join( QStringLiteral( " AND " ) );

          QgsAttributeList subset = attrs;
          subset << mReferencedLayer->fields().lookupField( fieldName );

          QgsFeatureIterator it( mReferencedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( expression ).setSubsetOfAttributes( subset ) ) );

          bool found = false;
          while ( it.nextFeature( f ) )
          {
            if ( !featureIds.contains( f.id() ) )
              featureIds << f.id();

            found = true;
          }

          // item is only provided if at least 1 feature exists
          if ( found )
            texts << txt;
        }

        texts.sort();
        cb->addItems( texts );

        cb->setEnabled( true );
        cb->blockSignals( false );

        ccb = cb;
      }
    }
  }
  filterExpression = filters.values().join( QStringLiteral( " AND " ) );
  mComboBox->setFilterExpression( filterExpression );
}
Example #25
0
int InputConvertUnitsParametersDialog::getEMode()const
{
  return m_emode->currentIndex();
}
Example #26
0
QString QmitkToFRecorderWidget::getSaveFileName(mitk::ToFImageWriter::ToFImageType& tofImageType,
                                     bool& distanceImageSelected,
                                     bool& amplitudeImageSelected,
                                     bool& intensityImageSelected,
                                     bool& rgbImageSelected,
                                     bool& rawDataSelected,
                                     QWidget *parent,
                                     const QString &caption,
                                     const QString &dir,
                                     const QString &filter,
                                     QString *selectedFilter,
                                     QFileDialog::Options options
                                     )
{
  QString selectedFileName = "";
  QComboBox* combo = new QComboBox;
  combo->addItem("3D");
  combo->addItem("2D + t");

  QHBoxLayout* checkBoxGroup = new QHBoxLayout();

  QCheckBox* distanceImageCheckBox = new QCheckBox;
  distanceImageCheckBox->setText("Distance image");
  distanceImageCheckBox->setChecked(distanceImageSelected);
  QCheckBox* amplitudeImageCheckBox = new QCheckBox;
  amplitudeImageCheckBox->setText("Amplitude image");
  amplitudeImageCheckBox->setChecked(amplitudeImageSelected);
  QCheckBox* intensityImageCheckBox = new QCheckBox;
  intensityImageCheckBox->setText("Intensity image");
  intensityImageCheckBox->setChecked(intensityImageSelected);
  QCheckBox* rgbImageCheckBox = new QCheckBox;
  rgbImageCheckBox->setText("RGB image");
  rgbImageCheckBox->setChecked(rgbImageSelected);
  QCheckBox* rawDataCheckBox = new QCheckBox;
  rawDataCheckBox->setText("Raw data");
  rawDataCheckBox->setChecked(false);
  rawDataCheckBox->setEnabled(false);

  checkBoxGroup->addWidget(distanceImageCheckBox);
  checkBoxGroup->addWidget(amplitudeImageCheckBox);
  checkBoxGroup->addWidget(intensityImageCheckBox);
  checkBoxGroup->addWidget(rgbImageCheckBox);
  checkBoxGroup->addWidget(rawDataCheckBox);

  QFileDialog* fileDialog = new QFileDialog(parent, caption, dir, filter);

  QLayout* layout = fileDialog->layout();
  QGridLayout* gridbox = qobject_cast<QGridLayout*>(layout);

  if (gridbox)
  {
    gridbox->addWidget(new QLabel("ToF-Image type:"));
    gridbox->addWidget(combo);
    int lastRow = gridbox->rowCount();
    gridbox->addLayout(checkBoxGroup, lastRow, 0, 1, -1);
  }

  fileDialog->setLayout(gridbox);
  fileDialog->setAcceptMode(QFileDialog::AcceptSave);

  if (selectedFilter)
  {
    fileDialog->selectNameFilter(*selectedFilter);
  }

  if (fileDialog->exec() == QDialog::Accepted)
  {
    if (selectedFilter)
    {
      *selectedFilter = fileDialog->selectedFilter();
    }

    if (combo->currentIndex() == 0)
    {
      tofImageType = mitk::ToFImageWriter::ToFImageType3D;
    }

    else
    {
      tofImageType = mitk::ToFImageWriter::ToFImageType2DPlusT;
    }

    distanceImageSelected = distanceImageCheckBox->isChecked();
    amplitudeImageSelected = amplitudeImageCheckBox->isChecked();
    intensityImageSelected = intensityImageCheckBox->isChecked();
    rgbImageSelected = rgbImageCheckBox->isChecked();
    rawDataSelected = rawDataCheckBox->isChecked();

    selectedFileName = fileDialog->selectedFiles().value(0);
  }

  delete fileDialog;
  return selectedFileName;
}
Example #27
0
void TankUseDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const
{
	QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
	model->setData(index, comboBox->currentIndex());
}
void MTPageNym_AltLocation::on_lineEditItemValue_textChanged(const QString & text)
{
    QLineEdit* edit = qobject_cast<QLineEdit*>(sender());

    if (edit)
    {
        // The data has just changed.

        // Update the internal data representation so the caller who
        // instantiated the wizard can get to it after the wizard is
        // closed.
        //
        PrepareOutputData();
        // ----------------------------------------------------------
        // Make sure there is at least one empty item in this group.
        //
        QWidget * pContactItemWidget = VPtr<QWidget>::asPtr(edit->property("contactitemwidget"));

        if (nullptr == pContactItemWidget)
        {
            return;
        }
        // ----------------------------------------------------------
        QComboBox * pComboBox = VPtr<QComboBox>::asPtr(pContactItemWidget->property("combo"));

        if (nullptr == pComboBox)
        {
            return;
        }
        // ----------------------------------------------------------
        GroupBoxContactItems * pGroupBox = VPtr<GroupBoxContactItems>::asPtr(pContactItemWidget->property("groupbox"));

        if (nullptr == pGroupBox)
        {
            return;
        }

        QLayout * pGroupBoxLayout = pGroupBox->layout();
        // ----------------------------------------------------------
        bool bAtLeastOneIsEmpty = false;

        for (int index_widget = 0; index_widget < pGroupBoxLayout->count(); ++index_widget)
        {
            QWidget *pItemWidget = pGroupBoxLayout->itemAt(index_widget)->widget();
            if (nullptr != pItemWidget)
            {
                const int nIndexLineEdit = 1; // todo hardcoding.
                QLayout * pItemLayout = pItemWidget->layout(); // Combo, Line Edit, Button
                QWidget *pLineEditWidget = pItemLayout->itemAt(nIndexLineEdit)->widget();

                if (nullptr != pLineEditWidget)
                {
                    QLineEdit * pLineEdit = dynamic_cast<QLineEdit *>(pLineEditWidget);
                    if (nullptr != pLineEdit)
                    {
                        const QString & qstrText = pLineEdit->text();

                        if (qstrText.isEmpty())
                        {
                            bAtLeastOneIsEmpty = true;
                            break;
                        }
                    }
                }
            }
        } // item widgets on group box.
        // -----------------------------------
        if (!bAtLeastOneIsEmpty)
        {
            QWidget * pNewItem = createSingleContactItem(pGroupBox, pComboBox->currentIndex());

            if (nullptr != pNewItem)
            {
                pGroupBoxLayout->addWidget(pNewItem);
            }
        }
    }
}
schedulerTypes TaskAllocationWindow::getScheduler(unsigned int cpuIndex){
    QComboBox *box = this->cpuBoxMap[cpuIndex];
    return (schedulerTypes) box->currentIndex();
}
void ChannelRoutingDelegate::setModelData ( QWidget* pEditor,
	QAbstractItemModel *pModel, const QModelIndex& index ) const
{
	QComboBox *pComboBox = static_cast<QComboBox*> (pEditor);
	pModel->setData(index, pComboBox->currentIndex());
}