void SifGenerator::handleCheckBox(const QDomElement &elem, QWidget *widget)
{
  QString name = elem.firstChildElement("SifName").text().trimmed();
  if( name == "" )
    name = elem.firstChildElement("Name").text().trimmed();
  
  QString def_val = elem.firstChildElement("DefaultValue").text().trimmed();
  if ( def_val == "" )
    def_val = "False";

  QCheckBox *checkBox = static_cast<QCheckBox*>(widget);
  
  if(checkBox->isChecked()) {
    if ( def_val != "True" )
      te->append("  " + name + " = True");
  } else {
    if ( def_val != "False" )
      te->append("  " + name + " = False");
  }
}
Exemple #2
0
QStringList ITranslatable::toText()
{
    QStringList output;
    QMap<QString,QWidget*> paramMap = getParameterMap();
    QMap<QString,QWidget*>::iterator it = paramMap.begin();

    for (it; it != paramMap.end(); ++it) {
        QWidget* p = it.value();
        if (!p->isVisible())
            //Don't output non-visible params
            continue;
        QString key = it.key();
        QString out = key + " = ";
        //Is text type
        QLineEdit* l = dynamic_cast<QLineEdit*>(p);
        if (l) {
            out += l->text();
            output << out;
            continue;
        }
        //Is checkbox type.
        QCheckBox* b = dynamic_cast<QCheckBox*>(p);
        if (b) {
            if (b->isChecked())
                out += "yes";
            else
                out += "no";
            output << out;
            continue;
        }
        //Is combobox type.
        QComboBox* c = dynamic_cast<QComboBox*>(p);
        if (c) {
            out += c->currentText();
            output << out;
            continue;
        }
    }

    return output;
}
void ReportUser::on_pushButton_clicked()
{
    this->ui->pushButton->setEnabled(false);
    // we need to get a report info for all selected diffs
    QString reports = "";
    int xx = 0;
    int EvidenceID = 0;
    while (xx < this->ui->tableWidget->rowCount())
    {
        if (this->CheckBoxes.count() > xx)
        {
            QCheckBox *checkBox = (QCheckBox*)this->ui->tableWidget->cellWidget(xx, 4);
            if (checkBox->isChecked())
            {
                ++EvidenceID;
                reports += "[[Special:Diff/" + this->ui->tableWidget->item(xx, 3)->text() + "|" +
                           QString::number(EvidenceID) + "]] ";
            }
        }
        ++xx;
    }
    if (reports.isEmpty())
    {
        QMessageBox::StandardButton mb;
        mb = QMessageBox::question(this, "Question", _l("report-evidence-none-provid"), QMessageBox::Yes|QMessageBox::No);
        if (mb == QMessageBox::No)
        {
            this->ui->pushButton->setEnabled(true);
            return;
        }
    }
    // obtain current page
    this->Loading = true;
    this->ui->pushButton->setText(_l("report-retrieving"));
    this->qHistory = Generic::RetrieveWikiPageContents(this->ReportedUser->GetSite()->GetProjectConfig()->ReportAIV, this->ReportedUser->GetSite());
    this->qHistory->Site = this->ReportedUser->GetSite();
    this->qHistory->Process();
    this->ReportText = reports;
    this->tReportUser->start(HUGGLE_TIMER);
    return;
}
void
SaveOnExitDialogWidget::saveClicked()
{
    // whizz through the list and save one by one using
    // singleSave to ensure warnings are given if neccessary
    // use mainWindow->ismultisave to prevent refreshing stats
    // for each file
    mainWindow->ismultisave = true;
    for (int i=0; i<dirtyList.count(); i++) {
        QCheckBox *c = (QCheckBox *)dirtyFiles->cellWidget(i,0);
        if (c->isChecked()) {
            if (i==dirtyList.count()-1) {
                mainWindow->ismultisave = false;
            }
            mainWindow->saveRideSingleDialog(dirtyList.at(i));
        }
    }

    mainWindow->ismultisave = false;
    accept();
}
Exemple #5
0
		void Persistence::Store(QWidget* widget, QString storageName) {
			if (storageName.isEmpty()) storageName = widget->objectName();
			if (qobject_cast<QLineEdit*>(widget)) {
				QLineEdit* lineEdit = qobject_cast<QLineEdit*>(widget); 
				GetStore()[storageName] = QVariant(lineEdit->text());
			} else if (qobject_cast<QCheckBox*>(widget)) {
				QCheckBox* cb = qobject_cast<QCheckBox*>(widget); 
				GetStore()[storageName] = QVariant(cb->isChecked());
			} else if (qobject_cast<QSpinBox*>(widget)) {
				QSpinBox* sb = qobject_cast<QSpinBox*>(widget); 
				GetStore()[storageName] = QVariant(sb->value());
			} else if (qobject_cast<QRadioButton*>(widget)) {
				QRadioButton* rb = qobject_cast<QRadioButton*>(widget); 
				GetStore()[storageName] = QVariant(rb->isChecked());
			} else if (qobject_cast<QComboBox*>(widget)) {
				QComboBox* cb = qobject_cast<QComboBox*>(widget); 
				GetStore()[storageName] = QVariant(cb->currentText());
			} else {
				WARNING("Unsupported widget: " + widget->objectName());
			}
		}
bool CLedInfoDialog::SelectTarget( )
{
    QString strChk = "chk%1";
    bool bRet = false;

    for ( int nIndex = 1; nIndex <= 4; nIndex++ ) {
        QCheckBox* pChk = findChild< QCheckBox* >( strChk.arg( nIndex ) );
        bRet = pChk->isChecked( );

        if ( bRet ) {
            break;
        }
    }

    if ( !bRet ) {
        CCommonFunction::MsgBox( NULL, CCommonFunction::GetMsgTitle( QMessageBox::Information ),
                                 QString( "请选择信息发布目标!" ), QMessageBox::Information, "background-image: url( );" );
    }

    return bRet;
}
QString QgsSpatialQueryDialog::getDescriptionLayerShow( bool isTarget )
{
  QgsVectorLayer* lyr = NULL;
  QCheckBox * checkBox = NULL;
  if ( isTarget )
  {
    lyr = mLayerTarget;
    checkBox = ckbUsingSelectedTarget;
  }
  else
  {
    lyr = mLayerReference;
    checkBox = ckbUsingSelectedReference;
  }

  QString sDescFeatures = checkBox->isChecked()
                          ? tr( "%1 of %2" ).arg( lyr->selectedFeatureCount() ).arg( lyr->featureCount() )
                          : tr( "all = %1" ).arg( lyr->featureCount() );

  return QString( "%1 (%2)" ).arg( lyr->name() ).arg( sDescFeatures );
} // QString QgsSpatialQueryDialog::getDescriptionLayerShow(bool isTarget)
void MySqlRelationDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if (!index.isValid())
        return;

    QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel *>(model);
    QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    if (!sqlModel || !childModel || !combo) {
        if (HandbookDialog::m_record.fieldName(index.column()).contains("IS_", Qt::CaseSensitive))
        {
            QCheckBox * checkBox = qobject_cast<QCheckBox *>(editor);
            sqlModel->setData(index, checkBox->isChecked(), Qt::DisplayRole);
            sqlModel->setData(index, checkBox->isChecked(), Qt::EditRole);
            return;
        }
        else if (HandbookDialog::m_record.fieldName(index.column()).contains("DATE_", Qt::CaseSensitive))
        {
            QDateEdit * dateEdit = qobject_cast<QDateEdit *>(editor);
            sqlModel->setData(index, dateEdit->date().toString("yyyy-MM-dd"), Qt::DisplayRole);
            sqlModel->setData(index, dateEdit->date().toString("yyyy-MM-dd"), Qt::EditRole);
            return;
        }
        else
        {
            QItemDelegate::setModelData(editor, model, index);
            return;
        }
    }

    int currentItem = combo->currentIndex();
    int childColIndex = childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn());
    int childEditIndex = childModel->fieldIndex(sqlModel->relation(index.column()).indexColumn());
    sqlModel->setData(index,
            childModel->data(childModel->index(currentItem, childColIndex), Qt::DisplayRole),
            Qt::DisplayRole);
    sqlModel->setData(index,
            childModel->data(childModel->index(currentItem, childEditIndex), Qt::EditRole),
            Qt::EditRole);
}
void NotifyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
    if (edit) {
        model->setData(index, edit->text());
    } else {
        QComboBox * repeatEditor = qobject_cast<QComboBox *>(editor);
        if (repeatEditor) {
            model->setData(index, repeatEditor->currentText());
        } else {
            QSpinBox * expireEditor = qobject_cast<QSpinBox *>(editor);
            if (expireEditor) {
                model->setData(index, expireEditor->value(), Qt::EditRole);
            } else {
                QCheckBox* enablePlayEditor = qobject_cast<QCheckBox*>(editor);
                if (enablePlayEditor) {
                    model->setData(index, enablePlayEditor->isChecked(), Qt::EditRole);
                }
            }
        }
    }
}
	foreach (QObject* o, children()){
		QWidget* w = qobject_cast<QWidget*> (o);
		if (!w) continue;
		if (w->property("storage").isValid()){
			void* storage = w->property("storage").value<void*>();
			if (!storage) continue;
			//get value of the
			QCheckBox* checkBox = qobject_cast<QCheckBox*>(w);
			if (checkBox) {
				*((bool*)storage) = checkBox->isChecked();
				continue;
			}
			QLineEdit* edit = qobject_cast<QLineEdit*>(w);
			if (edit){
				*((QString*)storage) = edit->text();
				continue;
			}
			QTextEdit* tedit = qobject_cast<QTextEdit*>(w);
			if (tedit){
				*((QString*)storage) = tedit->toPlainText();
				continue;
			}
			QDoubleSpinBox* doubleSpinBox = qobject_cast<QDoubleSpinBox*>(w);
			if (doubleSpinBox){
				*((float*)storage) = doubleSpinBox->value();
				continue;
			}
			QSpinBox* spinBox = qobject_cast<QSpinBox*>(w);
			if (spinBox){
				*((int*)storage) = spinBox->value();
				continue;
			}
			QComboBox* comboBox = qobject_cast<QComboBox*>(w);
			if (comboBox){
				*((QStringList*)storage) = QStringList(comboBox->currentText());
				continue;
			}
		}
	}
QVariant WidgetParameters::getValue(QWidget* curWidget)
{

    QLineEdit* lineEdit = dynamic_cast<QLineEdit*>(curWidget);
    if(lineEdit)
        return lineEdit->text();

    QScienceSpinBox* dblspinbox = dynamic_cast<QScienceSpinBox*>(curWidget);
    if(dblspinbox)
        return dblspinbox->value();

    QSpinBox* spinbox = dynamic_cast<QSpinBox*>(curWidget);
    if(spinbox)
        return spinbox->value();

    QCheckBox* checkbox = dynamic_cast<QCheckBox*>(curWidget);
    if(checkbox)
        return checkbox->isChecked();

    QComboBox* combo = dynamic_cast<QComboBox*>(curWidget);
    if(combo)
        return combo->itemData(combo->currentIndex());
}
Exemple #12
0
void Notepadqq::showQtVersionWarning(bool showCheckBox, QWidget *parent)
{
    QSettings settings;
    QString dir = QDir::toNativeSeparators(QDir::homePath() + "/Qt");
    QString altDir = "/opt/Qt";

    QMessageBox msgBox(parent);
    msgBox.setWindowTitle(QCoreApplication::applicationName());
    msgBox.setIcon(QMessageBox::Warning);
    msgBox.setText("<h3>" + QObject::tr("You are using an old version of Qt (%1)").arg(qVersion()) + "</h3>");
    msgBox.setInformativeText("<html><body>"
        "<p>" + QObject::tr("Notepadqq will try to do its best, but <b>some things will not work properly</b>.") + "</p>" +
        QObject::tr(
            "Install a newer Qt version (&ge; %1) from the official repositories "
            "of your distribution.<br><br>"
            "If it's not available, download Qt (&ge; %1) from %2 and install it to \"%3\" or to \"%4\".").
                  arg("5.3").
                  arg("<nobr><a href=\"http://qt-project.org/\">http://qt-project.org/</a></nobr>").
                  arg("<nobr>" + dir + "</nobr>").
                  arg("<nobr>" + altDir + "</nobr>") +
        "</body></html>");

    QCheckBox *chkDontShowAgain;

    if (showCheckBox) {
        chkDontShowAgain = new QCheckBox();
        chkDontShowAgain->setText(QObject::tr("Don't show me this warning again"));
        msgBox.setCheckBox(chkDontShowAgain);
    }

    msgBox.exec();

    if (showCheckBox) {
        settings.setValue("checkQtVersionAtStartup", !chkDontShowAgain->isChecked());
        chkDontShowAgain->deleteLater();
    }
}
void ServiceItemDelegate::updateItemWidgets(const QList<QWidget*> widgets,
                                              const QStyleOptionViewItem& option,
                                              const QPersistentModelIndex& index) const
{
    QCheckBox* checkBox = static_cast<QCheckBox*>(widgets[0]);
    KPushButton *configureButton = static_cast<KPushButton*>(widgets[1]);

    const int itemHeight = sizeHint(option, index).height();

    // Update the checkbox showing the service name and icon
    const QAbstractItemModel* model = index.model();
    checkBox->setText(model->data(index).toString());
    const QString iconName = model->data(index, Qt::DecorationRole).toString();
    if (!iconName.isEmpty()) {
        checkBox->setIcon(KIcon(iconName));
    }
    checkBox->setChecked(model->data(index, Qt::CheckStateRole).toBool());

    const bool configurable = model->data(index, ServiceModel::ConfigurableRole).toBool();

    int checkBoxWidth = option.rect.width();
    if (configurable) {
        checkBoxWidth -= configureButton->sizeHint().width();
    }
    checkBox->resize(checkBoxWidth, checkBox->sizeHint().height());
    checkBox->move(0, (itemHeight - checkBox->height()) / 2);

    // Update the configuration button
    if (configurable) {
        configureButton->setEnabled(checkBox->isChecked());
        configureButton->setIcon(KIcon("configure"));
        configureButton->resize(configureButton->sizeHint());
        configureButton->move(option.rect.right() - configureButton->width(),
                              (itemHeight - configureButton->height()) / 2);
    }
    configureButton->setVisible(configurable);
}
Exemple #14
0
void MainWindow::getReminder() {
    // pull random from list
    if (m_reminderList->isEmpty()) {
        // show a text instead of a reminder
        m_text->append("There are no reminders to show.");
    }
    else {
        int rand = random(m_reminderList->length());
        QString rem = m_reminderList->at(rand);

         // show dialog
        QMessageBox reply;
        reply.setIcon(QMessageBox::Information);
        QCheckBox * check = new QCheckBox("Show this message again");
        check->setChecked(true);
        reply.setCheckBox(check);
        reply.setText(rem);
        reply.exec();

        if (!check->isChecked()) {
            m_reminderList->removeAt(rand);
        }
    }
}
Exemple #15
0
void SettingsDialog::changeAllAssociation(bool checked)
{
    int size = gridLayout->count();
    QCheckBox *cb;
    for(int i = 0; i < size; ++i){
        cb = dynamic_cast<QCheckBox*>(gridLayout->itemAt(i)->widget());
        if (cb) {
            if (cb->isChecked() == checked)
                continue;

            QString ext(cb->text());
            if(checked){
                OSRelated::setAssociation(ext);
            }else{
                OSRelated::clearAssociation(ext);
            }
            cb->setChecked(checked);
        }
    }

    OSRelated::refreshExplorer();

    reviewCheckAllButtonState();
}
QString QgsSpatialQueryDialog::getDescriptionInvalidFeaturesShow( bool isTarget )
{
  QgsVectorLayer* lyr = NULL;
  QCheckBox* checkBox = NULL;
  int totalInvalid = 0;
  if ( isTarget )
  {
    lyr = mLayerTarget;
    checkBox = ckbUsingSelectedTarget;
    totalInvalid = mFeatureInvalidTarget.size();
  }
  else
  {
    lyr = mLayerReference;
    checkBox = ckbUsingSelectedReference;
    totalInvalid = mFeatureInvalidReference.size();
  }

  QString sDescFeatures = checkBox->isChecked()
                          ? tr( "%1 of %2(selected features)" ).arg( totalInvalid ).arg( lyr->selectedFeatureCount() )
                          : tr( "%1 of %2" ).arg( totalInvalid ).arg( lyr->featureCount() );

  return QString( "%1: %2" ).arg( lyr->name() ).arg( sDescFeatures );
} // QString QgsSpatialQueryDialog::getDescriptionInvalidFeatures(bool isTarget)
void DialogActiveRunways::on_buttonOK_clicked()
{
    activeRunways->clearActiveAirports();

    QString tempAirport = "";

    for(int i = 0; i < model->rowCount(); i++)
    {
        QCheckBox *boxAirportDep = dynamic_cast<QCheckBox*>(uiInner->tableViewRunways->indexWidget(model->index(i, 0))->layout()->itemAt(0)->widget());
        QCheckBox *boxAirportArr = dynamic_cast<QCheckBox*>(uiInner->tableViewRunways->indexWidget(model->index(i, 1))->layout()->itemAt(0)->widget());
        QCheckBox *boxRunwayDep = nullptr;
        QCheckBox *boxRunwayArr = nullptr;

        if(uiInner->tableViewRunways->indexWidget(model->index(i, 4)) != nullptr) boxRunwayDep = dynamic_cast<QCheckBox*>(uiInner->tableViewRunways->indexWidget(model->index(i, 4))->layout()->itemAt(0)->widget());
        if(uiInner->tableViewRunways->indexWidget(model->index(i, 5)) != nullptr) boxRunwayArr = dynamic_cast<QCheckBox*>(uiInner->tableViewRunways->indexWidget(model->index(i, 5))->layout()->itemAt(0)->widget());

        bool boxAirportDepChecked = boxAirportDep->isChecked();
        bool boxAirportArrChecked = boxAirportArr->isChecked();
        bool boxRunwayDepChecked = false;
        bool boxRunwayArrChecked = false;

        if(boxRunwayDep != nullptr) boxRunwayDepChecked = boxRunwayDep->isChecked();
        if(boxRunwayArr != nullptr) boxRunwayArrChecked = boxRunwayArr->isChecked();

        if(boxAirportDepChecked || boxAirportArrChecked || boxRunwayDepChecked || boxRunwayArrChecked)
        {
            QString airport = model->index(i, 2).data().toString();

            if(airport != tempAirport) //Create new ActiveAirport
            {
                ActiveAirport activeAirport;

                activeAirport.airportCode = airport;
                if(boxAirportDepChecked) activeAirport.dep = true;
                if(boxAirportArrChecked) activeAirport.arr = true;
                if(boxRunwayDepChecked) activeAirport.depRwys.append(model->index(i, 3).data().toString());
                if(boxRunwayArrChecked) activeAirport.arrRwys.append(model->index(i, 3).data().toString());

                activeRunways->appendActiveAirport(activeAirport);

                tempAirport = airport;
            }
            else //Append data to last ActiveAirport
            {
                ActiveAirport activeAirport = activeRunways->getActiveAirport(activeRunways->getActiveAirports().size() - 1);

                if(boxRunwayDepChecked)
                {
                    activeAirport.depRwys.append(model->index(i, 3).data().toString());
                    activeRunways->getActiveAirports().replace(activeRunways->getActiveAirports().size() - 1, activeAirport);
                }

                if(boxRunwayArrChecked)
                {
                    activeAirport.arrRwys.append(model->index(i, 3).data().toString());
                    activeRunways->getActiveAirports().replace(activeRunways->getActiveAirports().size() - 1, activeAirport);
                }
            }
        }
    }

    emit closed();
    close();
}
Exemple #18
0
// ---------------------------------------------------------------
void LibraryDialog::slotCreateNext()
{
  if(NameEdit->text().isEmpty()) {
    QMessageBox::critical(this, tr("Error"), tr("Please insert a library name!"));
    return;
  }

  int count=0;
  QCheckBox *p;
  QListIterator<QCheckBox *> i(BoxList);
  while(i.hasNext()){
    p = i.next();
    if(p->isChecked()) {
      SelectedNames.append(p->text());
      Descriptions.append("");
      count++;
    }
  }

  if(count < 1) {
    QMessageBox::critical(this, tr("Error"), tr("Please choose at least one subcircuit!"));
    return;
  }

  LibDir = QDir(SimguiSettings.SimguiHomeDir);
  if(!LibDir.cd("user_lib")) { // user library directory exists ?
    if(!LibDir.mkdir("user_lib")) { // no, then create it
      QMessageBox::warning(this, tr("Warning"),
                   tr("Cannot create user library directory !"));
      return;
    }
    LibDir.cd("user_lib");
  }

  LibFile.setName(SimguiSettings.LibDir + NameEdit->text() + ".lib");
  if(LibFile.exists()) {
    QMessageBox::critical(this, tr("Error"), tr("A system library with this name already exists!"));
    return;
  }

  LibFile.setName(LibDir.absFilePath(NameEdit->text()) + ".lib");
  if(LibFile.exists()) {
    QMessageBox::critical(this, tr("Error"), tr("A library with this name already exists!"));
    return;
  }

  if (checkDescr->checkState() == Qt::Checked){
    // user enter descriptions
    stackedWidgets->setCurrentIndex(1);  // subcircuit description view

    checkedCktName->setText(SelectedNames[0]);
    textDescr->setText(Descriptions[0]);

    if (SelectedNames.count() == 1){
        prevButt->setDisabled(true);
        nextButt->setDisabled(true);
        createButt->setEnabled(true);
      }
  }
  else {
      // save whitout description
      emit slotSave();
  }
}
void InspectorImage::valueChanged(int idx)
      {
      QDoubleSpinBox* b1 = b.sizeWidth;
      QDoubleSpinBox* b2 = b.sizeHeight;
      QDoubleSpinBox* b3 = b.scaleWidth;
      QDoubleSpinBox* b4 = b.scaleHeight;
      Image* image = static_cast<Image*>(inspector->element());
      if (idx == ImageControl::AUTOSCALE) {
            bool v = !b.autoscale->isChecked();
            b1->setEnabled(v);
            b2->setEnabled(v);
            b.scaleWidth->setEnabled(v);
            b.scaleHeight->setEnabled(v);
            }
      if (idx == ImageControl::SIZE_W) {
            if (b.lockAspectRatio->isChecked()) {
                  QSizeF sz = image->getProperty(P_ID::SIZE).toSizeF();
                  qreal ratio = sz.width() / sz.height();
                  qreal h     = b1->value() / ratio;
                  b2->blockSignals(true);
                  b2->setValue(h);
                  b2->blockSignals(false);
                  InspectorBase::valueChanged(SIZE_H);
                  }
            updateScaleFromSize(QSizeF(b1->value(), b2->value()));
            }
      else if (idx == ImageControl::SIZE_H) {
            if (b.lockAspectRatio->isChecked()) {
                  QSizeF sz   = image->getProperty(P_ID::SIZE).toSizeF();
                  qreal ratio = sz.width() / sz.height();
                  qreal w     = b2->value() * ratio;
                  b1->blockSignals(true);
                  b1->setValue(w);
                  b1->blockSignals(false);
                  InspectorBase::valueChanged(ImageControl::SIZE_W);
                  }
            updateScaleFromSize(QSizeF(b1->value(), b2->value()));
            }
      else if (idx == ImageControl::SCALE_W) {
            if (b.lockAspectRatio->isChecked()) {
/* ImageControl::LOCK_RATIO keeps original ratio:
//      NEEDS case "else if(idx == ImageControl::LOCK_RATIO) ..." to restore original ratio on checking ImageControl::LOCK_RATIO
                  b4->blockSignals(true);
                  b4->setValue(b3->value());
                  b4->blockSignals(false);*/
/* ImageControl::LOCK_RATIO keeps current ratio: */
                  QSizeF sz   = inspector->element()->getProperty(P_ID::SCALE).toSizeF();
                  qreal ratio = sz.width() / sz.height();
                  qreal w     = b3->value() / ratio;
                  b4->blockSignals(true);
                  b4->setValue(w);
                  b4->blockSignals(false);
                  InspectorBase::valueChanged(ImageControl::SCALE_H);
                  }
            updateSizeFromScale(QSizeF(b3->value(), b4->value()));
            }
      else if (idx == SCALE_H) {
            if (b.lockAspectRatio->isChecked()) {
/* ImageControl::LOCK_RATIO keeps original ratio:
//      NEEDS case "else if(idx == ImageControl::LOCK_RATIO) ..." to restore original ratio on checking ImageControl::LOCK_RATIO
                  b3->blockSignals(true);
                  b3->setValue(b4->value());
                  b3->blockSignals(false);*/
/* ImageControl::LOCK_RATIO keeps current ratio: */
                  QSizeF sz   = inspector->element()->getProperty(P_ID::SCALE).toSizeF();
                  qreal ratio = sz.width() / sz.height();
                  qreal w     = b4->value() * ratio;
                  b3->blockSignals(true);
                  b3->setValue(w);
                  b3->blockSignals(false);
                  InspectorBase::valueChanged(ImageControl::SCALE_W);
                  }
            updateSizeFromScale(QSizeF(b3->value(), b4->value()));
            }
      else if (idx == SIZE_IS_SPATIUM) {
            QCheckBox* cb = static_cast<QCheckBox*>(iList[idx].w);
            qreal _spatium = inspector->element()->spatium();
            b1->blockSignals(true);
            b2->blockSignals(true);
            if (cb->isChecked()) {
                  b1->setSuffix("sp");
                  b2->setSuffix("sp");
                  b1->setValue(b1->value() * DPMM / _spatium);
                  b2->setValue(b2->value() * DPMM / _spatium);
                  }
            else {
                  b1->setSuffix("mm");
                  b2->setSuffix("mm");
                  b1->setValue(b1->value() * _spatium / DPMM);
                  b2->setValue(b2->value() * _spatium / DPMM);
                  }
            b1->blockSignals(false);
            b2->blockSignals(false);
            }
      InspectorBase::valueChanged(idx);
      }
Exemple #20
0
void KviModeEditor::commit()
{
	if(!m_pChannel)
	{
		emit done();
		return;
	}

	QMap<char, QString> szPlusModes;
	QMap<char, QString> szMinusModes;

	QCheckBox * pCheckBox;
	QLineEdit * pLineEdit;
	char cMode = 0;

	QList<char> modes = m_pCheckBoxes.keys();

	for(int i = 0; i < modes.count(); ++i)
	{
		cMode = modes.at(i);
		pCheckBox = m_pCheckBoxes.value(cMode);
		if(!pCheckBox)
			continue; // wtf!?

		pLineEdit = m_pLineEdits.value(cMode);
		if(pLineEdit)
		{
			// mode with parameter (with an exception)
			if(pCheckBox->isChecked())
			{
				// mode is checked
				if(!m_pChannel->hasChannelMode(cMode) || (pLineEdit->text().trimmed() != m_pChannel->channelModeParam(cMode)))
				{
					// mode was not checked before, or the parameter has changed
					szPlusModes.insert(cMode, pLineEdit->text().trimmed());
				}
			}
			else
			{
				// mode is not checked
				if(m_pChannel->hasChannelMode(cMode))
				{
					// but it was checked before

					// checks if this specific mode does not need a parameter when set
					if(modeNeedsParameterOnlyWhenSet(cMode))
					{
						szMinusModes.insert(cMode, QString());
					}
					else
					{
						szMinusModes.insert(cMode, m_pChannel->channelModeParam(cMode));
					}
				}
			}
		}
		else
		{
			//mode without parameter
			if(pCheckBox->isChecked())
			{
				if(!m_pChannel->plainChannelMode().contains(cMode))
					szPlusModes.insert(cMode, QString());
			}
			else
			{
				if(m_pChannel->plainChannelMode().contains(cMode))
					szMinusModes.insert(cMode, QString());
			}
		}
	}

	// now flush out mode changes
	int iModesPerLine = 3; // a good default
	KviIrcConnectionServerInfo * pServerInfo = nullptr;
	if(m_pChannel)
		pServerInfo = m_pChannel->serverInfo();
	if(pServerInfo)
	{
		iModesPerLine = pServerInfo->maxModeChanges();
		if(iModesPerLine < 1)
			iModesPerLine = 1;
	}

	QString szModes;
	QStringList szParameters;
	int iModes = 0;

	QMap<char, QString>::const_iterator iter = szMinusModes.constBegin();
	while(iter != szMinusModes.constEnd())
	{
		if(iter == szMinusModes.constBegin())
			szModes.append("-");
		szModes.append(iter.key());
		szParameters.append(iter.value());
		++iModes;
		++iter;

		//time to commit?
		if(iModes == iModesPerLine)
		{
			QString szCommitModes = szModes;
			if(iter == szMinusModes.constEnd())
				szModes.clear();
			else
				szModes = "-";
			if(szParameters.count())
			{
				szCommitModes.append(QChar(' '));
				szCommitModes.append(szParameters.join(QString(" ")));
				szParameters.clear();
			}
			iModes = 0;

			emit setMode(szCommitModes);
		}
	}

	iter = szPlusModes.constBegin();
	while(iter != szPlusModes.constEnd())
	{
		if(iter == szPlusModes.constBegin())
			szModes.append("+");
		szModes.append(iter.key());
		szParameters.append(iter.value());
		++iModes;
		++iter;

		//time to commit? this should be an ==, but includes the minus sign so "+aaa" = 4 chars
		if(iModes == iModesPerLine)
		{
			QString szCommitModes = szModes;
			if(iter == szPlusModes.constEnd())
				szModes.clear();
			else
				szModes = "+";
			if(szParameters.count())
			{
				szCommitModes.append(QChar(' '));
				szCommitModes.append(szParameters.join(QString(" ")));
				szParameters.clear();
			}
			iModes = 0;

			emit setMode(szCommitModes);
		}
	}

	if(iModes)
	{
		QString szCommitModes = szModes;
		szModes.clear();
		if(szParameters.count())
		{
			szCommitModes.append(QChar(' '));
			szCommitModes.append(szParameters.join(QString(" ")));
			szParameters.clear();
		}
		emit setMode(szCommitModes);
	}

	emit done();
}
Exemple #21
0
QString JabberSearch::condition()
{
    QString res;
	if (m_bXData)
		res += "x:data";

    QObjectList *l = queryList("QLineEdit");
    QObjectListIt it( *l );
    QObject *obj;

    while ((obj = it.current()) != 0 ){
        QLineEdit *edit = static_cast<QLineEdit*>(obj);
        if (!edit->text().isEmpty()){
            if (!res.isEmpty())
                res += ";";
            res += edit->name();
            res += "=";
            res += quoteChars(edit->text(), ";");
        }
        ++it;
    }
    delete l;

    l = queryList("QComboBox");
    QObjectListIt it1( *l );
    while ((obj = it1.current()) != 0 ){
        CComboBox *box = static_cast<CComboBox*>(obj);
        if (box->currentText().isEmpty())
            continue;
        if (!res.isEmpty())
            res += ";";
        res += box->name();
        res += "=";
        res += quoteChars(box->value(), ";");
        ++it1;
    }
    delete l;

    l = queryList("QCheckBox");
    QObjectListIt it2( *l );
    while ((obj = it2.current()) != 0 ){
        QCheckBox *box = static_cast<QCheckBox*>(obj);
        if (!box->isChecked())
            continue;
        if (!res.isEmpty())
            res += ";";
        res += box->name();
        res += "=1";
        ++it2;
    }
    delete l;

    if (!m_key.empty()){
        if (!res.isEmpty())
            res += ";";
        res += "key=";
        res += quoteChars(QString::fromUtf8(m_key.c_str()), ";");
    }

    return res;
}
void RuleDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    KLineEdit *ruleLineEdit = static_cast<KLineEdit*>(editor->layout()->itemAt(0)->widget());
    KComboBox *matchComboBox = static_cast<KComboBox*>(editor->layout()->itemAt(1)->widget());
    QCheckBox *requiredCheckBox = static_cast<QCheckBox*>(editor->layout()->itemAt(2)->widget());

    model->setData(index, ((matchComboBox->currentIndex() > 0)?(QString("%1+%2+%3").arg(requiredCheckBox->isChecked()?'1':'0').arg(matchComboBox->currentIndex()).arg(ruleLineEdit->text())):QString()), Qt::EditRole);
}
	void writeToProperty(value_type& v)
	{
		v = (m_checkBox->isChecked() ? 1 : 0);
	}
	void readFromProperty(const value_type& v)
	{
		bool b = (v!=0);
		if (m_checkBox->isChecked() != b)
			m_checkBox->setChecked(b);
	}
Exemple #25
0
void ApplicationWindow::ctrlAction(int id)
{
	unsigned ctrl_class = V4L2_CTRL_ID2CLASS(id);
	if (ctrl_class == V4L2_CID_PRIVATE_BASE)
		ctrl_class = V4L2_CTRL_CLASS_USER;
	unsigned ctrl = id & 0xffff;
	QCheckBox *cbox = static_cast<QCheckBox *>(widgetMap[ctrl_class | CTRL_UPDATE_ON_CHANGE]);
	bool update = cbox->isChecked();
	bool all = (ctrl == CTRL_UPDATE || (update && ctrl == CTRL_UPDATE_ON_CHANGE));

	if (ctrl == CTRL_DEFAULTS) {
		setDefaults(ctrl_class);
		return;
	}
	if (ctrl == CTRL_REFRESH) {
		refresh(ctrl_class);
		return;
	}
	if (!update && !all && ctrlMap[id].type != V4L2_CTRL_TYPE_BUTTON)
		return;
	if (ctrl_class == V4L2_CTRL_CLASS_USER) {
		if (!all) {
			updateCtrl(id);
			return;
		}
		for (unsigned i = 0; i < classMap[ctrl_class].size(); i++) {
			updateCtrl(classMap[ctrl_class][i]);
		}
		return;
	}
	if (!all) {
		updateCtrl(id);
		return;
	}
	unsigned count = classMap[ctrl_class].size();
	struct v4l2_ext_control *c = new v4l2_ext_control[count];
	struct v4l2_ext_controls ctrls;
	int idx = 0;

	for (unsigned i = 0; i < count; i++) {
		unsigned id = classMap[ctrl_class][i];

		if (ctrlMap[id].flags & (V4L2_CTRL_FLAG_READ_ONLY | V4L2_CTRL_FLAG_INACTIVE))
			continue;
		c[idx].id = id;
		if (ctrlMap[id].type == V4L2_CTRL_TYPE_INTEGER64)
			c[idx].value64 = getVal64(id);
		else
			c[idx].value = getVal(id);
		idx++;
	}
	memset(&ctrls, 0, sizeof(ctrls));
	ctrls.count = idx;
	ctrls.ctrl_class = ctrl_class;
	ctrls.controls = c;
	if (::ioctl(fd, VIDIOC_S_EXT_CTRLS, &ctrls)) {
		int err = errno;

		if (ctrls.error_idx >= ctrls.count) {
			printf("error: %s\n", strerror(err));
		}
		else {
			id = c[ctrls.error_idx].id;
			printf("error %08x (%s): %s\n", id,
					ctrlMap[id].name, strerror(err));
		}
	}
	delete [] c;
	refresh(ctrl_class);
}
void Database_Items::updateCurrentItem()
{
	if (itemRef != NULL)
	{
		Item::WeaponItem *weaponData;
		Item::EquipmentItem *equipmentData;
		Item::MedicineItem *medicineData;
		Item::SkillBookItem *skillBookData;
		Item::SeedItem *seedData;
		Item::SkillScrollItem *skillScrollData;
		Item::SwitchItem *switchData;
		Item::EventItem *eventData;
		StorageFile storageFile;
		int itemType = cboxType->currentIndex();
		(*itemRef)->setName(leName->text());
		(*itemRef)->setPrice(sbPrice->value());
		(*itemRef)->setType(itemType);
		if (itemType == Item::TYPE_COMMONITEM)
			(*itemRef)->setDescription(commonItem_leDescription->text());
		else if (itemType == Item::TYPE_WEAPON)
		{
			weaponData = (*itemRef)->getWeaponData();
			weaponData->twoHanded = rbBothHands->isChecked();
			(*itemRef)->setDescription(weapon_leDescription->text());
			weaponData->skillID = weapon_cboxSkill->currentIndex() - 1;
			weaponData->usableByCharacters = weapon_rbUsableByCharacter->isChecked();
			weaponData->usableBy.clear();
			for (int i = 0; i < weapon_twCharacterClassList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)weapon_twCharacterClassList->cellWidget(i, 0);
				weaponData->usableBy.append(checkBox->isChecked());
			}
			weaponData->attackChange = weapon_sbAttackChange->value();
			weaponData->defenseChange = weapon_sbDefenseChange->value();
			weaponData->wisdomChange = weapon_sbWisdomChange->value();
			weaponData->agilityChange = weapon_sbAgilityChange->value();
			weaponData->alwaysAttackFirst = weapon_cbAttackFirst->isChecked();
			weaponData->attackTwice = weapon_cbAttackTwice->isChecked();
			weaponData->attackAllEnemies = weapon_cbAttackAllEnemies->isChecked();
			weaponData->ignoreEnemyEvasion = weapon_cbIgnoreEnemyEvasion->isChecked();
			weaponData->cursed = weapon_cbCursed->isChecked();
			weaponData->usableOnTheDead = weapon_cbUsableOnTheDead->isChecked();
			weaponData->battleAnimationID = weapon_cboxBattleAnimation->currentIndex();
			weaponData->amountMPConsumed = weapon_sbMPConsumed->value();
			weaponData->percentHitProbability = weapon_sbHitProbability->value();
			weaponData->percentCriticalBonus = weapon_sbCriticalBonus->value();
			weaponData->attribute.clear();
			for (int i = 0; i < weapon_twAttributeList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)weapon_twAttributeList->cellWidget(i, 0);
				weaponData->attribute.append(checkBox->isChecked());
			}
			weaponData->conditions.clear();
			for (int i = 0; i < weapon_twConditionList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)weapon_twConditionList->cellWidget(i, 0);
				weaponData->conditions.append(checkBox->isChecked());
			}
			weaponData->inflictConditions = weapon_rbInflictCondition->isChecked();
			weaponData->percentConditionEffectivenessProbability = weapon_sbConditionEffectiveness->value();
			TODO("Handle weaponData->animationSettings");
		}
		else if (itemType == Item::TYPE_SHIELD || itemType == Item::TYPE_ARMOR || itemType == Item::TYPE_HELMET || itemType == Item::TYPE_ACCESSORY)
		{
			equipmentData = (*itemRef)->getEquipmentData();
			(*itemRef)->setDescription(equipment_leDescription->text());
			equipmentData->usableByCharacters = equipment_rbUsableByCharacter->isChecked();
			equipmentData->usableBy.clear();
			for (int i = 0; i < equipment_twCharacterClassList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)equipment_twCharacterClassList->cellWidget(i, 0);
				equipmentData->usableBy.append(checkBox->isChecked());
			}
			equipmentData->attackChange = equipment_sbAttackChange->value();
			equipmentData->defenseChange = equipment_sbDefenseChange->value();
			equipmentData->wisdomChange = equipment_sbWisdomChange->value();
			equipmentData->agilityChange = equipment_sbAgilityChange->value();
			equipmentData->preventCriticalHits = equipment_cbPreventCriticalHits->isChecked();
			equipmentData->increaseEvasion = equipment_cbIncreaseEvasion->isChecked();
			equipmentData->halfMPConsumption = equipment_cbHalfMPConsumption->isChecked();
			equipmentData->cursed = equipment_cbCursed->isChecked();
			equipmentData->attributeResistance.clear();
			for (int i = 0; i < equipment_twResistance->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)equipment_twResistance->cellWidget(i, 0);
				equipmentData->attributeResistance.append(checkBox->isChecked());
			}
			equipmentData->conditions.clear();
			for (int i = 0; i < equipment_twConditions->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)equipment_twConditions->cellWidget(i, 0);
				equipmentData->conditions.append(checkBox->isChecked());
			}
			equipmentData->resistConditions = equipment_rbResistCondition->isChecked();
			equipmentData->percentConditionResistanceEffectiveness = equipment_sbResistance->value();
		}
		else if (itemType == Item::TYPE_MEDICINE)
		{
			medicineData = (*itemRef)->getMedicineData();
			medicineData->numberOfUses = cboxNumberOfUses->currentIndex();
			(*itemRef)->setDescription(medicine_leDescription->text());
			medicineData->targetSingleAlly = medicine_rbTargetSingleAlly->isChecked();
			medicineData->usableByCharacters = medicine_rbUsableByCharacter->isChecked();
			medicineData->usableBy.clear();
			for (int i = 0; i < medicine_twCharacterClassList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)medicine_twCharacterClassList->cellWidget(i, 0);
				medicineData->usableBy.append(checkBox->isChecked());
			}
			medicineData->cureCondition.clear();
			for (int i = 0; i < medicine_twConditionList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)medicine_twConditionList->cellWidget(i, 0);
				medicineData->cureCondition.append(checkBox->isChecked());
			}
			medicineData->percentRestoredHP = medicine_sbPercentHPRecovery->value();
			medicineData->amountRestoredHP = medicine_sbAmountHPRecovery->value();
			medicineData->percentRestoredMP = medicine_sbPercentMPRecovery->value();
			medicineData->amountRestoredMP = medicine_sbAmountMPRecovery->value();
			medicineData->onlyUsableOnFieldMap = medicine_cbFieldMapOnly->isChecked();
			medicineData->onlyUsableOnDeadCharacters = medicine_cbDeadCharactersOnly->isChecked();
		}
		else if (itemType == Item::TYPE_SKILLBOOK)
		{
			skillBookData = (*itemRef)->getSkillBookData();
			skillBookData->numberOfUses = cboxNumberOfUses->currentIndex();
			(*itemRef)->setDescription(skillBook_leDescription->text());
			skillBookData->usableByCharacters = skillBook_rbUsableByCharacter->isChecked();
			skillBookData->usableBy.clear();
			for (int i = 0; i < skillBook_twCharacterClassList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)skillBook_twCharacterClassList->cellWidget(i, 0);
				skillBookData->usableBy.append(checkBox->isChecked());
			}
			skillBookData->skillID = skillBook_cboxSkillLearned->currentIndex();
		}
		else if (itemType == Item::TYPE_SEED)
		{
			seedData = (*itemRef)->getSeedData();
			seedData->numberOfUses = cboxNumberOfUses->currentIndex();
			(*itemRef)->setDescription(seed_leDescription->text());
			seedData->usableByCharacters = seed_rbUsableByCharacter->isChecked();
			seedData->usableBy.clear();
			for (int i = 0; i < seed_twCharacterClassList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)seed_twCharacterClassList->cellWidget(i, 0);
				seedData->usableBy.append(checkBox->isChecked());
			}
			seedData->maxHPChange = seed_sbMaxHPChange->value();
			seedData->maxMPChange = seed_sbMaxMPChange->value();
			seedData->attackChange = seed_sbAttackChange->value();
			seedData->defenseChange = seed_sbDefenseChange->value();
			seedData->wisdomChange = seed_sbWisdomChange->value();
			seedData->agilityChange = seed_sbAgilityChange->value();
		}
		else if (itemType == Item::TYPE_SKILLSCROLL)
		{
			skillScrollData = (*itemRef)->getSkillScrollData();
			skillScrollData->numberOfUses = cboxNumberOfUses->currentIndex();
			(*itemRef)->setDescription(skillScroll_leDescription->text());
			skillScrollData->usableByCharacters = skillScroll_rbUsableByCharacter->isChecked();
			skillScrollData->usableBy.clear();
			for (int i = 0; i < skillScroll_twCharacterClassList->rowCount(); ++i)
			{
				QCheckBox *checkBox = (QCheckBox*)skillScroll_twCharacterClassList->cellWidget(i, 0);
				skillScrollData->usableBy.append(checkBox->isChecked());
			}
			skillScrollData->skillID = skillScroll_cboxSkillInvoked->currentIndex();
			skillScrollData->showItemNameMessageWhenUsed = skillScroll_rbItemName->isChecked();
		}
		else if (itemType == Item::TYPE_SWITCH)
		{
			switchData = (*itemRef)->getSwitchData();
			switchData->numberOfUses = cboxNumberOfUses->currentIndex();
			(*itemRef)->setDescription(switch_leDescription->text());
			switchData->switchID = ProjectData::switchVariableIdFromString(switch_lwSwitch->item(0)->text());
			switchData->allowFieldActivation = switch_cbAllowField->isChecked();
			switchData->allowBattleActivation = switch_cbAllowBattle->isChecked();
		}
		else if (itemType == Item::TYPE_EVENT)
		{
			eventData = (*itemRef)->getEventData();
			eventData->numberOfUses = cboxNumberOfUses->currentIndex();
			(*itemRef)->setDescription(event_leDescription->text());
			eventData->allowFieldActivation = event_cbAllowField->isChecked();
			eventData->allowBattleActivation = event_cbAllowBattle->isChecked();
			TODO("Handle eventData->event");
		}
	}
}
void
CQGnuPlotDataDialog::
doPlot(bool add)
{
  CExpr *expr = window_->app()->expr();

  missingStr_ = missingEdit_->text().toStdString();

  //---

  Smooth smooth = Smooth::None;

  if      (averageCheck_->isChecked())
    smooth = Smooth::Average;
  else if (summedCheck_->isChecked())
    smooth = Smooth::Summed;

  //---

  // TODO: filter on plot

  CGnuPlotGroup *group;

  if (add) {
    group = window_->createTiledGroup();

    if (! group)
      return;
  }
  else {
    window_->initCurrentGroup();

    group = window_->currentGroup();

    if (! group)
      return;
  }

  QString usingStr = usingEdit_->text();
  QString indexStr = indexEdit_->text();
  QString everyStr = everyEdit_->text();
  QString whereStr = whereEdit_->text();

  CGnuPlotUsingCols usingCols(window_->app());
  CGnuPlotIndexData indexData;
  CGnuPlotEveryData everyData;
  CGnuPlotWhereData whereData;

  usingCols.parse(usingStr.toStdString());
  indexData.parse(expr, indexStr.toStdString());
  everyData.parse(expr, everyStr.toStdString());
  whereData.parse(whereStr.toStdString());

  CQGnuPlotDataModel *model = tree_->model();

  //---

  CQHeaderView *header = tree_->header();

  typedef std::set<int> Active;

  Active active;

  for (int c = 0; c < model->columnCount(); ++c) {
    QCheckBox *cb = qobject_cast<QCheckBox *>(header->widget(c));

    if (cb && cb->isChecked())
      active.insert(c);
  }

  //---

  bool is2D = dimension2DRadio_->isChecked();

  const CGnuPlotFile &file = model->file();

  CGnuPlotTypes::PlotStyle style = CQGnuPlotEnum::plotStyleConv(enum_->plotStyle());

  // single set, single subset
  if      (! model->isHierarchical1() && ! model->isHierarchical2()) {
    int setNum = 0;

    CGnuPlotPlotP plot = group->createNewPlot(style);

    initPlotStyle(plot);

    plot->setSetNum  (setNum);
    plot->setDataFile(file);

    plot->set2D(  is2D);
    plot->set3D(! is2D);

    plot->init();

    //---

    ValuesDataList valuesDataList;

    for (int lineNum = 0; lineNum < model->rowCount(); ++lineNum) {
      bool lineActive = (everyStr != "" ? everyData.validPointIndex(lineNum) : true);
      if (! lineActive) continue;

      CGnuPlotPlot::Values values;
      bool                 missing = false;

      for (int c = 0; c < model->columnCount(); ++c) {
        if (active.find(c) == active.end())
          continue;

        QModelIndex ind = model->index(lineNum, c);

        QVariant var = model->data(ind);

        std::string field = var.toString().toStdString();

        bool missing;

        CExprValuePtr value = fieldToValue(field, missing);

        if (missing)
          value->setMissing(true);

        values.push_back(value);
      }

      if (missing)
        continue;

      //---

      if (whereStr != "") {
        if (! whereData.isValid(expr, setNum, lineNum, values))
          continue;
      }

      //---

      CGnuPlot::Values newValues;
      bool             bad = false;
      CGnuPlot::Params params;

      if (usingStr != "")
        usingCols.decodeValues(0, setNum, lineNum, values, bad, newValues, params);
      else
        newValues = values;

      if (bad)
        continue;

      //---

      bool discontinuity = false;

      valuesDataList.push_back(ValuesData(newValues, discontinuity, bad, params));
    }

    if (smooth != Smooth::None)
      valuesDataList = smoothValuesList(valuesDataList, smooth);

    for (const auto &vd : valuesDataList) {
      if (is2D)
        plot->addPoint2D(vd.values, vd.discontinuity, vd.bad, vd.params);
      else
        plot->addPoint3D(0, vd.values, vd.discontinuity, vd.bad, vd.params);
    }
  }
  // single set, multiple subsets
  else if (model->isHierarchical1()) {
    int setNum = 0;

    CGnuPlotPlotP plot = group->createNewPlot(style);

    initPlotStyle(plot);

    plot->setSetNum  (setNum);
    plot->setDataFile(file);

    plot->set2D(  is2D);
    plot->set3D(! is2D);

    plot->init();

    //---

    for (int subSetNum = 0; subSetNum < model->rowCount(); ++subSetNum) {
      bool subSetActive = (everyStr != "" ? everyData.validBlockIndex(subSetNum) : true);
      if (! subSetActive) continue;

      QModelIndex ind = model->index(subSetNum, 0);

      //---

      ValuesDataList valuesDataList;

      for (int lineNum = 0; lineNum < model->rowCount(ind); ++lineNum) {
        bool lineActive = (everyStr != "" ? everyData.validPointIndex(lineNum) : true);
        if (! lineActive) continue;

        CGnuPlotPlot::Values values;

        for (int c = 0; c < model->columnCount(); ++c) {
          if (active.find(c) == active.end())
            continue;

          QModelIndex ind1 = model->index(lineNum, c, ind);

          QVariant var = model->data(ind1);

          std::string field = var.toString().toStdString();

          bool missing;

          CExprValuePtr value = fieldToValue(field, missing);

          if (missing)
            value->setMissing(true);

          values.push_back(value);
        }

        //---

        if (whereStr != "") {
          if (! whereData.isValid(expr, setNum, lineNum, values))
            continue;
        }

        //---

        CGnuPlot::Values newValues;
        bool             bad = false;
        CGnuPlot::Params params;

        if (usingStr != "")
          usingCols.decodeValues(0, setNum, lineNum, values, bad, newValues, params);
        else
          newValues = values;

        if (bad)
          continue;

        //---

        bool discontinuity = (subSetNum > 0 && lineNum == 0);

        valuesDataList.push_back(ValuesData(newValues, discontinuity, bad, params));
      }

      if (smooth != Smooth::None)
        valuesDataList = smoothValuesList(valuesDataList, smooth);

      for (const auto &vd : valuesDataList) {
        if (is2D)
          plot->addPoint2D(vd.values, vd.discontinuity, vd.bad, vd.params);
        else
          plot->addPoint3D(subSetNum, vd.values, vd.discontinuity, vd.bad, vd.params);
      }
    }
  }
  // multiple sets, multiple subsets
  else {
    CGnuPlotPlotP plot;

    // for 3D we want stack of plots (single set)
    if (! is2D) {
      int setNum = 0;

      plot = group->createNewPlot(style);

      initPlotStyle(plot);

      plot->setSetNum  (setNum);
      plot->setDataFile(file);

      plot->set2D(false);
      plot->set3D(true);

      plot->init();
    }

    //---

    for (int setNum = 0; setNum < model->rowCount(); ++setNum) {
      bool setActive = (indexStr != "" ? indexData.validIndex(setNum) : true);
      if (! setActive) continue;

      //---

      if (is2D) {
        plot = group->createNewPlot(style);

        initPlotStyle(plot);

        plot->setSetNum  (setNum);
        plot->setDataFile(file);

        plot->set2D(true);
        plot->set3D(false);

        plot->init();
      }

      //---

      QModelIndex ind = model->index(setNum, 0);

      for (int subSetNum = 0; subSetNum < model->rowCount(ind); ++subSetNum) {
        bool subSetActive = (everyStr != "" ? everyData.validBlockIndex(subSetNum) : true);
        if (! subSetActive) continue;

        QModelIndex ind1 = model->index(subSetNum, 0, ind);

        //---

        ValuesDataList valuesDataList;

        for (int lineNum = 0; lineNum < model->rowCount(ind1); ++lineNum) {
          bool lineActive = (everyStr != "" ? everyData.validPointIndex(lineNum) : true);
          if (! lineActive) continue;

          CGnuPlotPlot::Values values;

          for (int c = 0; c < model->columnCount(); ++c) {
            if (active.find(c) == active.end())
              continue;

            QModelIndex ind2 = model->index(lineNum, c, ind1);

            QVariant var = model->data(ind2);

            std::string field = var.toString().toStdString();

            bool missing;

            CExprValuePtr value = fieldToValue(field, missing);

            if (missing)
              value->setMissing(true);

            values.push_back(value);
          }

          //---

          if (whereStr != "") {
            if (! whereData.isValid(expr, setNum, lineNum, values))
              continue;
          }

          //---

          CGnuPlot::Values newValues;
          bool             bad = false;
          CGnuPlot::Params params;

          if (usingStr != "")
            usingCols.decodeValues(0, setNum, lineNum, values, bad, newValues, params);
          else
            newValues = values;

          if (bad)
            continue;

          //---

          bool discontinuity = (subSetNum > 0 && lineNum == 0);

          valuesDataList.push_back(ValuesData(newValues, discontinuity, bad, params));
        }

        if (smooth != Smooth::None)
          valuesDataList = smoothValuesList(valuesDataList, smooth);

        for (const auto &vd : valuesDataList) {
          if (is2D)
            plot->addPoint2D(vd.values, vd.discontinuity, vd.bad, vd.params);
          else
            plot->addPoint3D(subSetNum, vd.values, vd.discontinuity, vd.bad, vd.params);
        }
      }
    }
  }
}
bool GTUtilsOptionPanelMsa::isUseDotsOptionSet(GUITestOpStatus &os) {
    openTab(os, Highlighting);
    QCheckBox *useDots = GTWidget::findExactWidget<QCheckBox *>(os, "useDots");
    GT_CHECK_RESULT(NULL != useDots, "useDots checkbox is NULL", false);
    return useDots->isChecked();
}
Exemple #29
0
void FitDialog::accept()
{
	QString curve = boxCurve->currentText();
	QStringList curvesList = d_graph->curvesList();
	if (curvesList.contains(curve) <= 0)
	{
		QMessageBox::critical(this,tr("Warning"),
				tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!").arg(curve));
		boxCurve->clear();
		boxCurve->addItems(curvesList);
		return;
	}

	if (!validInitialValues())
		return;

	QString from=boxFrom->text().toLower();
	QString to=boxTo->text().toLower();
	QString tolerance=boxTolerance->text().toLower();
	double start, end, eps;
	try
	{
		MyParser parser;
		parser.SetExpr(CONFS(from).toAscii().constData());
		start=parser.Eval();
	}
	catch(mu::ParserError &e)
	{
		QMessageBox::critical(this, tr("Start limit error"),QString::fromStdString(e.GetMsg()));
		boxFrom->setFocus();
		return;
	}

	try
	{
		MyParser parser;
		parser.SetExpr(CONFS(to).toAscii().constData());
		end=parser.Eval();
	}
	catch(mu::ParserError &e)
	{
		QMessageBox::critical(this, tr("End limit error"),QString::fromStdString(e.GetMsg()));
		boxTo->setFocus();
		return;
	}

	if (start>=end)
	{
		QMessageBox::critical(0, tr("Input error"),
				tr("Please enter x limits that satisfy: from < end!"));
		boxTo->setFocus();
		return;
	}

	try
	{
		MyParser parser;
		parser.SetExpr(CONFS(tolerance).toAscii().constData());
		eps=parser.Eval();
	}
	catch(mu::ParserError &e)
	{
		QMessageBox::critical(0, tr("Tolerance input error"),QString::fromStdString(e.GetMsg()));
		boxTolerance->setFocus();
		return;
	}

	if (eps<0 || eps>=1)
	{
		QMessageBox::critical(0, tr("Tolerance input error"),
				tr("The tolerance value must be positive and less than 1!"));
		boxTolerance->setFocus();
		return;
	}

	int i, n=0, rows=boxParams->rowCount();
	if (!boxParams->isColumnHidden(2))
	{
		for (i=0;i<rows;i++)
		{//count the non-constant parameters
            QCheckBox *cb = (QCheckBox*)boxParams->cellWidget(i, 2);
			if (!cb->isChecked())
				n++;
		}
	}
	else
		n=rows;

	QStringList parameters;
	double *paramsInit = new double[n];
	QString formula;

	// recursively define variables for user functions used in formula
	bool found_uf;
	do {
		found_uf = false;
		for (i=0; i<d_user_function_names.count(); i++)
			if (boxFunction->text().contains(d_user_function_names[i])) {
				QStringList l = d_user_functions[i].split("=");
				formula += QString("%1=%2\n")
						.arg(d_user_function_names[i])
						.arg(l[1]);
				found_uf = true;
			}
	} while (found_uf);
	formula += boxFunction->text();

	// define variables for builtin functions used in formula
	for (i=0; i<d_built_in_function_names.count(); i++)
		if (formula.contains(d_built_in_function_names[i]))
			formula.prepend(QString("%1=%2\n")
					.arg(d_built_in_function_names[i])
					.arg(d_built_in_functions[i]));


        if (!boxParams->isColumnHidden(2))
        {
            int j = 0;
            for (i=0;i<rows;i++)
            {
                QCheckBox *cb = (QCheckBox*)boxParams->cellWidget(i, 2);
                if (!cb->isChecked())
                {
                    paramsInit[j] = QLocale().toDouble(boxParams->item(i,1)->text());
                    parameters << boxParams->item(i,0)->text();
                    j++;
                }
                else
                    formula.prepend(QString("%1=%2\n")
                                    .arg(boxParams->item(i,0)->text())
                                    .arg(CONFS(boxParams->item(i,1)->text())));
            }
        }
        else
        {
            for (i=0;i<n;i++)
            {
                paramsInit[i] = QLocale().toDouble(boxParams->item(i,1)->text());
                parameters << boxParams->item(i,0)->text();
            }
        }

        ApplicationWindow *app = (ApplicationWindow *)this->parent();

        if (d_fitter)
        {
            delete d_fitter;
            d_fitter  = 0;
        }

        if (boxUseBuiltIn->isChecked() && categoryBox->currentRow() == 1)
            fitBuiltInFunction(funcBox->currentItem()->text(), paramsInit);
        else if (boxUseBuiltIn->isChecked() && categoryBox->currentRow() == 3)
        {
            d_fitter = new PluginFit(app, d_graph);
            if (!((PluginFit*)d_fitter)->load(d_plugin_files_list[funcBox->currentRow()])){
                d_fitter  = 0;
                return;}
            d_fitter->setInitialGuesses(paramsInit);
        }
        else
        {
            d_fitter = new NonLinearFit(app, d_graph);
            ((NonLinearFit*)d_fitter)->setParametersList(parameters);
            ((NonLinearFit*)d_fitter)->setFormula(formula);
            d_fitter->setInitialGuesses(paramsInit);
        }
        delete[] paramsInit;

        if (!d_fitter->setDataFromCurve(curve, start, end) ||
            !d_fitter->setYErrorSource ((Fit::ErrorSource)boxYErrorSource->currentIndex(),
                                        tableNamesBox->currentText()+"_"+colNamesBox->currentText()))
        {
            delete d_fitter;
            d_fitter  = 0;
            return;
        }

        d_fitter->setTolerance (eps);
        d_fitter->setAlgorithm((Fit::Algorithm)boxAlgorithm->currentIndex());
        d_fitter->setColor(boxColor->currentIndex());
        d_fitter->generateFunction(generatePointsBtn->isChecked(), generatePointsBox->value());
        d_fitter->setMaximumIterations(boxPoints->value());
        d_fitter->scaleErrors(scaleErrorsBox->isChecked());

        if (d_fitter->name() == tr("MultiPeak") && ((MultiPeakFit *)d_fitter)->peaks() > 1)
        {
            ((MultiPeakFit *)d_fitter)->enablePeakCurves(app->generatePeakCurves);
            ((MultiPeakFit *)d_fitter)->setPeakCurvesColor(app->peakCurvesColor);
        }

        d_fitter->fit();
        double *res = d_fitter->results();
        if (!boxParams->isColumnHidden(2))
        {
            int j = 0;
            for (i=0;i<rows;i++)
            {
                QCheckBox *cb = (QCheckBox*)boxParams->cellWidget(i, 2);
                if (!cb->isChecked())
                    boxParams->item(i, 1)->setText(QLocale().toString(res[j++], 'g', boxPrecision->value()));
            }
        }
        else
        {
            for (i=0;i<rows;i++)
                boxParams->item(i, 1)->setText(QLocale().toString(res[i], 'g', boxPrecision->value()));
        }
}
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;
}