コード例 #1
0
ファイル: progManage.cpp プロジェクト: ngocthanhtnt/ledshow
void CprogManage::newScreen()
{
    //QTreeWidgetItem *curItem;
    //QTreeWidgetItem *parentItem;
    QString QStr;
    int i,size;//,type,index;
    int max = 0,tmp;

    if(verifyPSW() EQ 0)
        return;

    /*
    CinputPSWDialog *pswInput = new CinputPSWDialog(this);
    //pswInput->setOkButtonText(tr("确定"));
    pswInput->exec();
*/
    QStr = "screen";//QStr + "/" + QString(tr("area"));

    settings.beginGroup(QStr);
    QStringList groups = settings.childGroups(); //area列表

    size = groups.size();

    for(i = 0; i < size; i ++)
    {
      tmp = groups.at(i).toInt();
      if(tmp > max)
          max=tmp;
    }
    max++;


    //初始化分区属性
    settings.beginGroup(fixWidthNumber(max));
    settings.setValue("screenIndex", 1);//value("screenIndex").toString()
    settings.setValue("checkState", true);
    settings.setValue("spaceWidth", 1);
    settings.setValue("dotWidth", 2);
    settings.endGroup();
    settings.endGroup();


    //
    QTreeWidgetItem* item = new QTreeWidgetItem(treeWidget,QStringList(QString::number(size + 1)+tr("屏幕")));
    item->setData(0, Qt::UserRole, QVariant(QStr + "/" + fixWidthNumber(max)));
    item->setCheckState(0, Qt::Checked);

    QIcon icon = getTypeIcon(SCREEN_PROPERTY);
    item->setIcon(0,icon);

    treeWidget->addTopLevelItem(item);

    /*CMdiSubWindow * subWin =*/
    _newScreen(QString::number(size + 1) + tr("屏幕"), 0, 0, DEF_SCN_WIDTH, DEF_SCN_HEIGHT,1, 2, DEF_SCN_COLOR);
    w->screenArea->screenItem = item;

    w->progManage->treeWidget->setCurrentItem(item);

    //---------------
    QString str = w->screenArea->getCurrentScreenStr(); //当前屏幕str
    QDialog *facParaWin = new QDialog(this);
    QHBoxLayout *hLayout = new QHBoxLayout(facParaWin);

    facParaWin->setWindowTitle(tr("新建屏幕"));

    CcomTest *comTest = new CcomTest(facParaWin);
    CfacScreenProperty *facScreenProperty = new CfacScreenProperty(NEW_SCN, comTest, facParaWin);
    //facScreenProperty->setSettingsToWidget(str);

    hLayout->addWidget(facScreenProperty);
    hLayout->addWidget(comTest);

    facParaWin->setLayout(hLayout);
    facParaWin->setAttribute(Qt::WA_DeleteOnClose);
    connect(facScreenProperty->endButton, SIGNAL(clicked()), facParaWin, SLOT(close()));
    facParaWin->exec();
    //--------------------

    //判断参数是否被加载,没有被加载则删除已经生成的窗口
    settings.beginGroup(str);
    settings.beginGroup("facPara");
    int setFlag = settings.value("setFlag").toInt(); //是否加载设置了屏幕参数?
    settings.endGroup();
    settings.endGroup();

    if(setFlag EQ 0) //没有加载参数则删除上面建的屏幕
    {
       w->progManage->_deleteItem(0); //删除上面创建的屏幕
    }

    //读取屏幕参数
    //getScreenParaFromSettings(QStr + "/" + QString::number(max), Screen_Para);
    /*
    else
    {
       //subWin->resize(width + 8, height + 34);//setGeometry(0,0, width +8, height + 34);
       subWin->setFixedSize(width + 8, height + 34);
    }*/

}
コード例 #2
0
ファイル: DossierEditeur.cpp プロジェクト: atchandj/LO21
void DossierEditeur::ajouterInscription()
{
    try
    {
        QDialog* window = new QDialog(this);
        QGridLayout* lay = new QGridLayout;
        QPushButton* ok = new QPushButton("Ok");
        QComboBox *ListeUV= new QComboBox(this);
        QComboBox *ListeCursus= new QComboBox(this);
        QComboBox *ListeResultat= new QComboBox(this);
        QComboBox *ListeSaison= new QComboBox(this);
        QLineEdit *Annee= new QLineEdit(this);
        QLabel* UVLabel= new QLabel("UV : ",this);
        QLabel* cursusLabel= new QLabel("Cursus : ",this);
        QLabel* resultatLabel= new QLabel("Note : ",this);
        QLabel* saisonLabel= new QLabel("Saison : ",this);
        QLabel* anneeLabel = new QLabel("Année : ",this);
        window->setFixedSize(300, 400);

        UV** uvs = UVManager::getInstance().getUVs();
        for(unsigned int i=0;i<UVManager::getInstance().getNbUV(); i++)
        {
            ListeUV->addItem(uvs[i]->getCode());
        }


        for(Note n = first; n <= last; n = Note(n+1))
            ListeResultat->addItem(NoteToString(n));

        for(int i = 0; i < FormationManager::getInstance().getTaille(); i++)
            ListeCursus->addItem(FormationManager::getInstance().getElement(i).getCode());
        ListeSaison->addItem("Automne");
        ListeSaison->addItem("Printemps");

        lay->addWidget(UVLabel,0,0);
        lay->addWidget(cursusLabel,1,0);
        lay->addWidget(resultatLabel,2,0);
        lay->addWidget(saisonLabel,3,0);
        lay->addWidget(anneeLabel,4,0);
        lay->addWidget(ListeUV,0,1);
        lay->addWidget(ListeCursus,1,1);
        lay->addWidget(ListeResultat,2,1);
        lay->addWidget(ListeSaison,3,1);
        lay->addWidget(Annee,4,1);
        lay->addWidget(ok,5,1,Qt::AlignHCenter);

        window->setLayout(lay);

        connect(ok,SIGNAL(clicked()),window,SLOT(accept()));
        window->exec();

        if(window->result())
        {
            if(Annee->text().isEmpty())
                throw UTProfilerException("Ne laissez pas l'année vide !");

            UV& uv = UVManager::getInstance().getUV(ListeUV->currentText());
            Semestre s(StringToSaison(ListeSaison->currentText()),Annee->text().toUInt());
            Dossier::getInstance().ajouterInscription(uv,StringToNote(ListeResultat->currentText()),s,ListeCursus->currentText());
            QMessageBox::information(this,"Ajout d'une inscription", QString("Ajout de la catégorie ")+ListeUV->currentText()+" réussie.");
            dossier->setRowCount(Dossier::getInstance().getTaille());

            QTableWidgetItem *monItem = new QTableWidgetItem(ListeUV->currentText());
            dossier->setItem(Dossier::getInstance().getTaille() -1,0,monItem);

            monItem = new QTableWidgetItem(s.FormeContracte());
            dossier->setItem(Dossier::getInstance().getTaille() -1,1,monItem);

            monItem = new QTableWidgetItem(ListeResultat->currentText());
            dossier->setItem(Dossier::getInstance().getTaille() -1,2,monItem);

            monItem = new QTableWidgetItem(ListeCursus->currentText());
            dossier->setItem(Dossier::getInstance().getTaille() -1,3,monItem);
        }
    }
    catch(UTProfilerException& e)
    {
        QMessageBox::warning(this, "Ajout d'inscription", e.getInfo());
    }
}
コード例 #3
0
ファイル: detailedit.cpp プロジェクト: kazcw/Moneychanger
void MTDetailEdit::dialog(MTDetailEdit::DetailEditType theType, bool bIsModal/*=false*/)
{
    if (m_bFirstRun)
    {
        m_bFirstRun = false;
        // -------------------------------------------
        ui->tableWidget->setColumnCount(2);
        ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
        // -------------------------------------------
        ui->tableWidget->horizontalHeader()->resizeSection(0, 5);
        // -------------------------------------------
        ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
        ui->tableWidget->verticalHeader()->setDefaultSectionSize(60);
        ui->tableWidget->verticalHeader()->hide();
        ui->tableWidget->horizontalHeader()->hide();
        // -------------------------------------------
        ui->tableWidget->setContentsMargins(10,0,0,0);
        // -------------------------------------------
        ui->tableWidget->setSizePolicy(
                    QSizePolicy::Expanding,
                    QSizePolicy::Expanding);
        // ----------------------------------
        m_pTabWidget  = new QTabWidget;
        // ----------------------------------
        m_pTabWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        m_pTabWidget->setContentsMargins(5, 5, 5, 5);
        // ----------------------------------
        QWidget * pTab1 = new QWidget;
        // ----------------------------------
        pTab1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        pTab1->setContentsMargins(5, 5, 5, 5);
        // ----------------------------------
        m_pTabWidget->addTab(pTab1, tr("Details"));
        // -------------------------------------------
        // Instantiate m_pDetailPane to one of various types.
        //
        m_Type = theType;

        switch (m_Type)
        {
        case MTDetailEdit::DetailEditTypeNym:     m_pDetailPane = new MTNymDetails(this, *this);     break;
        case MTDetailEdit::DetailEditTypeContact: m_pDetailPane = new MTContactDetails(this, *this); break;
        case MTDetailEdit::DetailEditTypeServer:  m_pDetailPane = new MTServerDetails(this, *this);  break;
        case MTDetailEdit::DetailEditTypeAsset:   m_pDetailPane = new MTAssetDetails(this, *this);   break;

        case MTDetailEdit::DetailEditTypeAccount:
            m_pDetailPane = new MTAccountDetails(this, *this);
            // -------------------------------------------
            connect(m_pDetailPane,   SIGNAL(DefaultAccountChanged(QString, QString)),
                    m_pMoneychanger, SLOT  (setDefaultAccount(QString, QString)));
            // -------------------------------------------
//            connect(m_pDetailPane,   SIGNAL(cashBalanceChanged()),
//                    m_pMoneychanger, SLOT  (onCashBalanceChanged()));
//            // -------------------------------------------
//            connect(m_pDetailPane,   SIGNAL(acctBalanceChanged()),
//                    m_pMoneychanger, SLOT  (onAcctBalanceChanged()));
//            // -------------------------------------------
            break;
        default:
            qDebug() << "MTDetailEdit::dialog: MTDetailEdit::DetailEditTypeError";
            return;
        }
        // -------------------------------------------
        m_pDetailPane->SetOwnerPointer(*this);
        // -------------------------------------------
        m_pDetailLayout = new QVBoxLayout;
        m_pDetailLayout->addWidget(m_pDetailPane);

        m_pDetailPane  ->setContentsMargins(1,1,1,1);
        m_pDetailLayout->setContentsMargins(1,1,1,1);
        // ----------------------------------

        pTab1->setLayout(m_pDetailLayout);

        // ----------------------------------
        int nCustomTabCount = m_pDetailPane->GetCustomTabCount();

        if (nCustomTabCount > 0)
        {
            for (int ii = 0; ii < nCustomTabCount; ii++)
            {
                QWidget * pTab = m_pDetailPane->CreateCustomTab(ii);
                // ----------------------------------
                if (NULL != pTab)
                {
                    pTab->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
                    pTab->setContentsMargins(5, 5, 5, 5);

                    QString qstrTabName = m_pDetailPane->GetCustomTabName(ii);

                    m_pTabWidget->addTab(pTab, qstrTabName);
                }
                // ----------------------------------
            }
        }
        // -----------------------------------------------
        QGridLayout * pGridLayout = new QGridLayout;
        pGridLayout->addWidget(m_pTabWidget);

        pGridLayout->setContentsMargins(0,0,0,0);
        m_pTabWidget->setTabPosition(QTabWidget::South);
        // ----------------------------------
        ui->widget->setContentsMargins(1,1,1,1);
        // ----------------------------------
        ui->widget->setLayout(pGridLayout);
        // ----------------------------------
    } // first run.
    // -------------------------------------------
    RefreshRecords();
    // -------------------------------------------
//    if (m_map.size() < 1)
//        on_addButton_clicked();
    // -------------------------------------------
    if (bIsModal)
    {
        QDialog theDlg;
        theDlg.setWindowTitle(this->windowTitle());
//        theDlg.installEventFilter(this);

        QVBoxLayout * pLayout = new QVBoxLayout;

        pLayout->addWidget(this);

        theDlg.setLayout(pLayout);
        theDlg.setWindowFlags(Qt::Tool); // A hack so it will show the close button.
        theDlg.exec();

        pLayout->removeWidget(this);
    }
    else
    {
        this->installEventFilter(this);

        show();
        setFocus();
    }
    // -------------------------------------------
}
コード例 #4
0
QString AddImagesDialog::getDirectory(const QStringList &fileNames, const QString &defaultDirectory)
{
    QDialog *dialog = new QDialog(Core::ICore::dialogParent());
    dialog->setMinimumWidth(480);

    QString result;
    QString directory = defaultDirectory;

    dialog->setModal(true);
    dialog->setWindowFlags(dialog->windowFlags() & ~Qt::WindowContextHelpButtonHint);
    dialog->setWindowTitle(QCoreApplication::translate("AddImageToResources","Add Resources"));
    QTableWidget *table = createFilesTable(fileNames);
    table->setParent(dialog);
    QGridLayout *mainLayout = new QGridLayout(dialog);
    mainLayout->addWidget(table, 0, 0, 1, 4);

    QComboBox *directoryComboBox = createDirectoryComboBox(defaultDirectory);

    auto setDirectoryForComboBox = [directoryComboBox, &directory](const QString &newDir) {
        if (directoryComboBox->findText(newDir) < 0)
            directoryComboBox->addItem(newDir);

        directoryComboBox->setCurrentText(newDir);
        directory = newDir;
    };

    QObject::connect(directoryComboBox, &QComboBox::currentTextChanged, dialog, [&directory](const QString &text){
       directory = text;
    });

    QPushButton *browseButton = new QPushButton(QCoreApplication::translate("AddImageToResources", "&Browse..."), dialog);

    QObject::connect(browseButton, &QPushButton::clicked, dialog, [setDirectoryForComboBox, &directory]() {
        const QString newDir = QFileDialog::getExistingDirectory(Core::ICore::dialogParent(),
                                                              QCoreApplication::translate("AddImageToResources", "Target Directory"),
                                                              directory);
        if (!newDir.isEmpty())
            setDirectoryForComboBox(newDir);
    });

    mainLayout->addWidget(new QLabel(QCoreApplication::translate("AddImageToResources", "In directory:")), 1, 0);
    mainLayout->addWidget(directoryComboBox, 1, 0, 1, 3);
    mainLayout->addWidget(browseButton, 1, 3, 1 , 1);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
                                       | QDialogButtonBox::Cancel);

    mainLayout->addWidget(buttonBox, 3, 2, 1, 2);

    QObject::connect(buttonBox, &QDialogButtonBox::accepted, dialog, [dialog](){
        dialog->accept();
        dialog->deleteLater();
    });

    QObject::connect(buttonBox, &QDialogButtonBox::rejected, dialog, [dialog, &directory](){
        dialog->reject();
        dialog->deleteLater();
        directory = QString();
    });

    QObject::connect(dialog, &QDialog::accepted, [&directory, &result](){
        result = directory;
    });

    dialog->exec();

    return result;
}
コード例 #5
0
void GettingStartedWelcomePageWidget::slotOpenExample()
{
    QAction *action = qobject_cast<QAction*>(sender());
    if (!action)
        return;

    QString helpFile = action->property(HelpPathPropertyName).toString();
    QString proFile = action->property(ExamplePathPropertyName).toString();
    QString qmlMainFileName;
    bool isQmlProject = false;
    if (action->dynamicPropertyNames().contains(QmlMainFileName)) {
        qmlMainFileName = action->property(QmlMainFileName).toString();
        isQmlProject = true;
    }
    QStringList files;

    QFileInfo proFileInfo(proFile);
    // If the Qt is a distro Qt on Linux, it will not be writable, hence compilation will fail
    if (!proFileInfo.isWritable())
    {
        QDialog d;
        QGridLayout *lay = new QGridLayout(&d);
        QLabel *descrLbl = new QLabel;
        d.setWindowTitle(tr("Copy Project to writable Location?"));
        descrLbl->setTextFormat(Qt::RichText);
        descrLbl->setWordWrap(true);
        descrLbl->setText(tr("<p>The project you are about to open is located in the "
                             "write-protected location:</p><blockquote>%1</blockquote>"
                             "<p>Please select a writable location below and click \"Copy Project and Open\" "
                             "to open a modifiable copy of the project or click \"Keep Project and Open\" "
                             "to open the project in location.</p><p><b>Note:</b> You will not "
                             "be able to alter or compile your project in the current location.</p>")
                          .arg(QDir::toNativeSeparators(proFileInfo.dir().absolutePath())));
        lay->addWidget(descrLbl, 0, 0, 1, 2);
        QLabel *txt = new QLabel(tr("&Location:"));
        Utils::PathChooser *chooser = new Utils::PathChooser;
        txt->setBuddy(chooser);
        chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);
        QSettings *settings = Core::ICore::instance()->settings();
        chooser->setPath(settings->value(
                QString::fromLatin1("General/ProjectsFallbackRoot"), QDir::homePath()).toString());
        lay->addWidget(txt, 1, 0);
        lay->addWidget(chooser, 1, 1);
        QDialogButtonBox *bb = new QDialogButtonBox;
        connect(bb, SIGNAL(accepted()), &d, SLOT(accept()));
        connect(bb, SIGNAL(rejected()), &d, SLOT(reject()));
        QPushButton *copyBtn = bb->addButton(tr("&Copy Project and Open"), QDialogButtonBox::AcceptRole);
        copyBtn->setDefault(true);
        bb->addButton(tr("&Keep Project and Open"), QDialogButtonBox::RejectRole);
        lay->addWidget(bb, 2, 0, 1, 2);
        connect(chooser, SIGNAL(validChanged(bool)), copyBtn, SLOT(setEnabled(bool)));
        if (d.exec() == QDialog::Accepted) {
            QString exampleDirName = proFileInfo.dir().dirName();
            QString toDir = chooser->path();
            settings->setValue(QString::fromLatin1("General/ProjectsFallbackRoot"), toDir);
            QDir toDirWithExamplesDir(toDir);
            if (toDirWithExamplesDir.cd(exampleDirName)) {
                toDirWithExamplesDir.cdUp(); // step out, just to not be in the way
                QMessageBox::warning(topLevelWidget(), tr("Warning"),
                                     tr("The specified location already exists. "
                                        "Please specify a valid location."),
                                     QMessageBox::Ok, QMessageBox::NoButton);
                return;
            } else {
                QDir from = proFileInfo.dir();
                from.cdUp();
                copyRecursive(from, toDir, exampleDirName);
                // set vars to new location
                proFileInfo = QFileInfo(toDir + '/'+ exampleDirName + '/' + proFileInfo.fileName());
                proFile = proFileInfo.absoluteFilePath();
            }
        }
    }

    QString tryFile;
    files << proFile;
    if (isQmlProject) {
        tryFile = proFileInfo.path() + '/' + "/main.qml";
        if(!QFile::exists(tryFile))
            tryFile = proFileInfo.path() + "/qml/" + qmlMainFileName + ".qml";
        // legacy qmlproject case
        if(!QFile::exists(tryFile))
            tryFile = proFileInfo.path() + '/' + qmlMainFileName + ".qml";
        if(QFile::exists(tryFile))
            files << tryFile;
    } else {
        tryFile = proFileInfo.path() + "/main.cpp";
        if(!QFile::exists(tryFile))
            tryFile = proFileInfo.path() + '/' + proFileInfo.baseName() + ".cpp";
    }
    Core::ICore::instance()->openFiles(files, static_cast<Core::ICore::OpenFilesFlags>(Core::ICore::SwitchMode | Core::ICore::StopOnLoadFail));
    if (!tryFile.isEmpty() && Core::EditorManager::instance()->hasEditor(tryFile) && !helpFile.isEmpty())
        slotOpenContextHelpPage(helpFile);
}
コード例 #6
0
ファイル: appwin-calculations.cpp プロジェクト: dmt4/ddplot
void AppWin::compareDisp()
{
  QString item,cstr;
  int i, pos, p1, p2,  n, d, comp, idx;
  bool ok, comparable;

  Ui::DCompareDisp ui;
  QDialog *dialog = new QDialog;
  ui.setupUi(dialog);

  // set up the data
  for (i=0; i<tabWidget->count(); i++) {
    item = plotWidget[i]->FName;
    
    // only the file name is printed
    item = QDir::current().relativeFilePath(item);
    ui.plot1->addItem(item);
    ui.plot2->addItem(item);
  }

  dialog->exec();
  ok = dialog->result()==QDialog::Accepted;

  if (ok) {
    p1 = ui.plot1->currentRow();
    p2 = ui.plot2->currentRow();
    if (p1==p2) {
      msgInfo(info_CompareSamePlots);
      return;
    }

    comp = EDGE * ui.compEdge->isChecked() + SCREW * ui.compScrew->isChecked();
    if (comp==EDGE) 
      cstr = QString(" (edge)");
    else 
      cstr = QString(" (screw)");

    // create a new widget
    PltWin *pw = new PltWin(tabWidget);
    *pw = *plotWidget[p1];
    
    // set the plot-specific parameters
    if (comp==EDGE)
      pw->DispComponent = DIFF_EDGE;  
    else if (comp==SCREW)
      pw->DispComponent = DIFF_SCREW;     
    pw->FName = tabWidget->tabText(p1) + " (-) " + tabWidget->tabText(p2) + cstr.toLatin1().data();

    comparable = pw->CompareDisp(plotWidget[p2], comp);
    if (!comparable) {
      delete(pw);
      msgError(err_CannotComparePlots);
      return;
    }

    plotWidget.append(pw);
    tabWidget->addTab(pw, pw->FName);
    tabWidget->setCurrentIndex(tabWidget->count()-1);
    tabWidget->show();

    idx = tabWidget->currentIndex();
    actFirstPlot->setEnabled(idx > 0);
    actPrevPlot->setEnabled(idx > 0);
    actNextPlot->setEnabled(idx < tabWidget->count()-1);
    actLastPlot->setEnabled(idx < tabWidget->count()-1);

    repaintStatusBar();
  }
}
コード例 #7
0
ファイル: mainwindow.cpp プロジェクト: AzanovAA/MediaRenamer
void MainWindow::filesRenamed(int count, int successCount)
{
//    QMessageBox *messageBox = new QMessageBox(this);
//    messageBox->setWindowTitle("Visual Renamer");
//    messageBox->setIconPixmap(QPixmap(":/resources/logo.png"));
//    messageBox->addButton(QMessageBox::Ok);

    if(count == successCount)
    {
        QDialog succesDialog;

        QLabel *logoLabel = new QLabel(&succesDialog);
        QLabel *messageLabel = new QLabel("All files have been\nrenamed successfully!", &succesDialog);
        QLabel *succesLabel = new QLabel(&succesDialog);
        QPushButton *okButton = new QPushButton("Ok");

        succesDialog.setStyleSheet("QFrame#add_files_frame {"
                             "border: 3px dashed rgb(220, 220, 220);"
                             "border-radius: 24px"
                             "}"
                             "QPushButton {"
                             "background: qlineargradient(x1:0.5, y1:0, x2:0.5, y2:1, stop:0 rgb(245, 245, 245), stop:1 rgb(214, 214, 214));"
                             "border: 1px solid rgb(171, 171, 171);"
                             "border-radius: 5px"
                             "}"
                             "QPushButton:pressed {"
                             "background: qlineargradient(x1:0.5, y1:0, x2:0.5, y2:1, stop:0 rgb(214, 214, 214), stop:1 rgb(230, 230, 230));"
                             "}"
                             "QWidget {"
                             "font: bold 13px \"Arial\";"
                             "color: rgb(58, 58, 58);"
                             "}");

        logoLabel->setPixmap(QPixmap(":/resources/logo.png"));
        succesLabel->setPixmap(QPixmap(":/resources/done.png"));
        messageLabel->setMargin(10);
        succesLabel->setMargin(10);

        okButton->setFixedSize(150, 30);

        QHBoxLayout *upperLayout = new QHBoxLayout;
        QVBoxLayout *mainLayout = new QVBoxLayout(&succesDialog);

        upperLayout->addWidget(logoLabel);
        upperLayout->addWidget(messageLabel);
        upperLayout->addWidget(succesLabel);

        mainLayout->addLayout(upperLayout);
        mainLayout->addWidget(okButton, 0, Qt::AlignHCenter);
        mainLayout->setSizeConstraint(QLayout::SetFixedSize);

        connect(okButton, SIGNAL(clicked()), &succesDialog, SLOT(accept()));

        succesDialog.exec();
    }
    else
    {
        QDialog failDialog;

        QLabel *logoLabel = new QLabel(&failDialog);
        QLabel *successMessageLabel = new QLabel(QString("%1 of %2 files have been\nrenamed successfully!").arg(successCount).arg(count), &failDialog);
        QLabel *failMessageLabel = new QLabel(QString("ERROR: %1 of %2 files\nhave not been renamed.").arg(count-successCount).arg(count), &failDialog);
        QLabel *succesLabel = new QLabel(&failDialog);
        QLabel *failLabel = new QLabel(&failDialog);

        QPushButton *okButton = new QPushButton("Ok");

        failDialog.setStyleSheet("QFrame#add_files_frame {"
                             "border: 3px dashed rgb(220, 220, 220);"
                             "border-radius: 24px"
                             "}"
                             "QPushButton {"
                             "background: qlineargradient(x1:0.5, y1:0, x2:0.5, y2:1, stop:0 rgb(245, 245, 245), stop:1 rgb(214, 214, 214));"
                             "border: 1px solid rgb(171, 171, 171);"
                             "border-radius: 5px"
                             "}"
                             "QPushButton:pressed {"
                             "background: qlineargradient(x1:0.5, y1:0, x2:0.5, y2:1, stop:0 rgb(214, 214, 214), stop:1 rgb(230, 230, 230));"
                             "}"
                             "QWidget {"
                             "font: bold 13px \"Arial\";"
                             "color: rgb(58, 58, 58);"
                             "}");

        logoLabel->setPixmap(QPixmap(":/resources/logo.png"));
        succesLabel->setPixmap(QPixmap(":/resources/done.png"));
        failLabel->setPixmap(QPixmap(":/resources/fail.png"));

        okButton->setFixedSize(150, 30);

        QVBoxLayout *messagesLayout = new QVBoxLayout;
        messagesLayout->addWidget(successMessageLabel);
        messagesLayout->addWidget(failMessageLabel);
        messagesLayout->setMargin(0);
        messagesLayout->setSpacing(0);

        QVBoxLayout *imagesLayout = new QVBoxLayout;
        imagesLayout->addWidget(succesLabel);
        imagesLayout->addWidget(failLabel);
        imagesLayout->setMargin(0);
        imagesLayout->setSpacing(0);

        QHBoxLayout *statusLayout = new QHBoxLayout;
        statusLayout->addLayout(messagesLayout);
        statusLayout->addLayout(imagesLayout);

        QHBoxLayout *upperLayout = new QHBoxLayout;
        upperLayout->addWidget(logoLabel);
        upperLayout->addLayout(statusLayout);

        QVBoxLayout *mainLayout = new QVBoxLayout(&failDialog);
        mainLayout->addLayout(upperLayout);
        mainLayout->addWidget(okButton, 0, Qt::AlignHCenter);
        mainLayout->setSizeConstraint(QLayout::SetFixedSize);

        connect(okButton, SIGNAL(clicked()), &failDialog, SLOT(accept()));

        failDialog.exec();
    }
}
コード例 #8
0
ファイル: mainwindow.cpp プロジェクト: lohasbai/Picture-Size
void MainWindow::ManipShow()
{
    QDialog *settings;
    QLabel *heightLabel, *widthLabel, *rotateLabel, *modeLabel, *methodLabel;
    QPushButton *confirmButton;
    QGridLayout *layout;

    settings = new QDialog;
    settings->setWindowTitle(tr("设置"));
    settings->setWindowIcon(QIcon("://icon/settingsIcon.png"));

    heightLabel = new QLabel(settings);
    QPixmap heightPix("://icon/heightIcon.png");
    heightLabel->setPixmap(heightPix);

    widthLabel = new QLabel(settings);
    QPixmap widthPix("://icon/widthIcon.png");
    widthLabel->setPixmap(widthPix);

    rotateLabel = new QLabel(settings);
    QPixmap rotatePix("://icon/rotateIcon.png");
    rotateLabel->setPixmap(rotatePix);

    modeLabel = new QLabel(settings);
    QPixmap modelPix("://icon/cropIcon.png");
    modeLabel->setPixmap(modelPix);

    methodLabel = new QLabel(settings);
    QPixmap methodPix("://icon/interIcon.png");
    methodLabel->setPixmap(methodPix);

    heightEdit = new QLineEdit(settings);
    heightEdit->setText("1");

    widthEdit = new QLineEdit(settings);
    widthEdit->setText("1");

    rotateEdit = new QLineEdit(settings);
    rotateEdit->setText("0");

    modeSelect = new QComboBox(settings);
    modeSelect->insertItem(0, tr("Crop"));
    modeSelect->insertItem(1, tr("Loose"));

    methodSelect = new QComboBox(settings);
    methodSelect->insertItem(0, tr("NearestNeighbor"));
    methodSelect->insertItem(1, tr("Bilinear"));
    methodSelect->insertItem(2, tr("Bicubic"));

    confirmButton = new QPushButton(settings);
    confirmButton->setText(tr("确定"));
    QObject::connect(confirmButton, SIGNAL(clicked()), this, SLOT(StartManipulate()));

    layout = new QGridLayout;
    layout->addWidget(heightLabel, 0, 0);
    layout->addWidget(widthLabel, 1, 0);
    layout->addWidget(rotateLabel, 2, 0);
    layout->addWidget(modeLabel, 3, 0);
    layout->addWidget(methodLabel, 4, 0);
    layout->addWidget(heightEdit, 0, 1);
    layout->addWidget(widthEdit, 1, 1);
    layout->addWidget(rotateEdit, 2, 1);
    layout->addWidget(modeSelect, 3, 1);
    layout->addWidget(methodSelect, 4, 1);
    layout->addWidget(confirmButton, 5, 0, 1, 2);

    settings->setLayout(layout);

    settings->exec();
}
コード例 #9
0
ファイル: main.cpp プロジェクト: dmitry-aka-jok/jpos2
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QApplication::setOrganizationName(_S("Majister"));
    QApplication::setApplicationName(_S("jPos"));

    qRegisterMetaType<SyncState>("SyncState");

    // Имя файла логов
    logFileName.clear();

    // Настройки базы - SQLite
    QString mainBase = _S("db.sqlite3");
    QString dbDriver = _S("QSQLITE");
    QString dbUser;
    QString dbPass;
    QString dbOptions;
    QString executeModule;
    QString executeParams;


    QString styleFileName;
    bool stylefree = false;

    //  Уровни лога, 1- только ошибки, 2 - основные действия, 3 - отладка каждого чиха
    int  loglevel = 1;
    //  Обнулить файл логов
    bool newlog        = false;
    bool resetSettings = false;
    bool showHelp      = false;
    bool saveSources   = false;


    QStringList args = QCoreApplication::arguments();
    for (int i = 1; i < args.count(); ++i)
    {
        QString value = args.at(i);

        if (value == _S("--logfile") && i < args.count())
        {
            logFileName = args.at(++i);
            continue;
        }

        if (value == _S("--loglevel") && i < args.count())
        {
            loglevel = args.at(++i).toInt();
            continue;
        }

        if (value == _S("--newlog"))
        {
            newlog = true;
            continue;
        }

        if (value == _S("--driver") && i < args.count())
        {
            dbDriver = args.at(++i);
            continue;
        }
        if (value == _S("--user") && i < args.count())
        {
            dbUser = args.at(++i);
            continue;
        }
        if (value == _S("--password") && i < args.count())
        {
            dbPass = args.at(++i);
            continue;
        }
        if (value == _S("--resetsettings"))
        {
            resetSettings = true;
            continue;
        }
        if (value == _S("--stylefree"))
        {
            stylefree = true;
            continue;
        }
        if (value == _S("--istyle") && i < args.count())
        {
            styleFileName = args.at(++i);
            continue;
        }
        if (value == _S("--version"))
        {
            qDebug() << _T("jPOS версия от %1 %2").arg(BUILDDATE).arg(BUILDTIME);
            return 0;
        }
        if (value == _S("--help"))
        {
            showHelp = true;
            break; // all other params not matter
        }
        if (value == _S("--sources"))
        {
            saveSources = true;
            break; // all other params not matter
        }
        if (value == _S("--execute") && i+1 < args.count())
        {
            executeModule = args.at(++i);
            executeParams = args.at(++i);
            continue;
        }
        // если не параметров - значит название базы
        mainBase = value;
    }


    if (saveSources)
    {
        QFile   sourcesFile(_S(":/sources/sources/sources.7z"));
        if(!sourcesFile.open(QFile::ReadOnly))
        {
            qDebug() << _T("%1 Ошибка доступа к исходникам: %2")
                        .arg(posForLog)
                        .arg(sourcesFile.errorString());
            return 1;
        }

        QFile   resultFile(_S("sources.7z"));
        if(!resultFile.open(QFile::WriteOnly))
        {
            qDebug() << _T("%1 Ошибка создания файла для сохранения: %2")
                        .arg(posForLog)
                        .arg(resultFile.errorString());
            return 1;
        }

        resultFile.write(sourcesFile.readAll());
        resultFile.close();
        sourcesFile.close();

        qDebug()<<"Исходники сохранены в файле sources.7z";
        return 0;
    }

    if (showHelp)
    {
        QFile   helpFile(_S(":/texts/texts/help.txt"));
        helpFile.open(QFile::ReadOnly);
        QString helpText = helpFile.readAll();
        qDebug() << _T("jPOS версия от %1 %2").arg(BUILDDATE).arg(BUILDTIME)<<endl;
        qDebug() << helpText;
        return 0;
    }

    if (newlog)
    {
        QFile::remove(logFileName);
    }


    if (!logFileName.isEmpty())
        qInstallMessageHandler(fileMessageHandler);
    //else
    //    qInstallMessageHandler(outputMessageHandler);


    if(!stylefree)
    {
        QFile styleFile;
        if(!styleFileName.isEmpty())
            styleFile.setFileName(styleFileName);
        else
            styleFile.setFileName(":/qss/qss/black-n-orange.qss");

        styleFile.open(QFile::ReadOnly);
        QString styleSheet = QString::fromLatin1(styleFile.readAll());
        qApp->setStyleSheet(styleSheet);
    }

    Datapipe               * data = new Datapipe();
    QMap<QString, QVariant>* vars = data->getVariables();

    if (loglevel > 0)
        qDebug() << _T("%1 Уровень лога: %2").arg(posForLog).arg(loglevel);

    vars->insert(_S("loglevel"), loglevel);


    QSettings *settings = data->getSettings();
    if (resetSettings)
        settings->clear();

    QStringList settingsKeys = settings->allKeys();

    QSettings *defaults = new QSettings(_S(":/defaults/defaults/globalsettings.ini"), QSettings::IniFormat);
    defaults->setIniCodec(QTextCodec::codecForName("UTF-8"));

    QStringList defaultKeys = defaults->allKeys();

    for (int i = 0; i < defaultKeys.count(); i++)
    {
        QString  key   = defaultKeys.at(i);
        QVariant value = defaults->value(key);

        if (!settingsKeys.contains(key))
            settings->setValue(key, value);
    }
    delete defaults;

    QFont font;
    font.setFamily(settings->value("global/default_font","DejaVu Sans").toString());
    font.setPixelSize(settings->value("global/default_font_size",14).toInt());
    font.setBold(settings->value("global/defalut_font_bold",true).toBool());

    qApp->setFont(font);


    // Финт - зададим дефолты для некоторых баз
    if((dbDriver=="QIBASE" || dbDriver=="QFIREBIRD") && dbUser.isEmpty())
        dbUser="******";
    if((dbDriver=="QIBASE" || dbDriver=="QFIREBIRD") && dbPass.isEmpty())
        dbPass="******";


    QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);

    db.setDatabaseName(mainBase);
    db.setUserName(dbUser);
    db.setPassword(dbPass);
    db.setConnectOptions(dbOptions);

    if (!db.open())
    {
        qCritical()<<_T("%1 Ошибка подключения: %2").arg(posForLog).arg(db.lastError().text());
        return 2;
    }

    if (loglevel > 0)
    {
        qDebug() << _T("%1 База данных: %2").arg(posForLog).arg(mainBase);
        qDebug() << _T("%1 Драйвер: %2").arg(posForLog).arg(dbDriver);
        qDebug() << _T("%1 Пользователь: %2").arg(posForLog).arg(dbUser);
        qDebug() << _T("%1 Пароль: %2").arg(posForLog).arg(dbPass);
        qDebug() << _T("%1 Настройки: %2").arg(posForLog).arg(dbOptions);
    }
    vars->insert(_S("database"), mainBase);
    vars->insert(_S("database_driver"), dbDriver);
    vars->insert(_S("database_user"), dbUser);
    vars->insert(_S("database_password"), dbPass);
    vars->insert(_S("database_settings"), dbOptions);

    QSqlQuery query;


    query.prepare(settings->value(_S("global/queries/settings")).toString());
    if (query.exec())
    {
        while (query.next())
        {
            vars->insert(query.value(0).toString(), query.value(1));
            if(loglevel > 0)
                qDebug() << _T("%1 Переменные: %2 = %3").arg(posForLog).arg(query.value(0).toString()).arg(query.value(1).toString());
        }
    }
    else
    {
        bool solved = false;
        if(dbDriver=="QSQLITE")
        {
            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(0,
                                          _T("Не обнаружена база данных"),
                                          _T("Не обнаружена база данных\nСоздать новую?"),
                                          QMessageBox::Yes|QMessageBox::No);

            if (reply == QMessageBox::Yes)
            {
                QFile file(":/defaults/defaults/database_sqlite.sql");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qCritical() << _T("%1 Ошибка создания новой базы данных\n%2").arg(posForLog).arg(file.errorString());
                    return  0;
                }


                QStringList queryPartsList = QString::fromUtf8(file.readAll()).split(QRegExp("\\s"), QString::SkipEmptyParts);

                int triggerDepth=0;
                int stringDepth=0;
                bool skipOneBegin=false;
                QString queryFromParts;

                for(int i=0; i<queryPartsList.count();++i)
                {
                    QString part = queryPartsList.at(i).trimmed();

                    if(part.isEmpty())
                        continue;

                    if(part.toUpper() == "CREATE" && i+1 < queryPartsList.count())
                        if(queryPartsList.at(i+1)=="TRIGGER")
                        {
                            triggerDepth++;
                            skipOneBegin=true;
                        }


                    if(triggerDepth > 0 && part.toUpper()=="BEGIN")
                    {
                        if(skipOneBegin)
                            skipOneBegin=false;
                        else
                            triggerDepth++;
                    }
                    if(triggerDepth > 0 && part.toUpper()=="CASE")
                            triggerDepth++;

                    if(triggerDepth > 0 && part.toUpper().startsWith("END"))
                            triggerDepth--;

                    queryFromParts += _S(" %1").arg(part);

                    //qDebug()<<part<<triggerDepth<<stringDepth;

                    if(part.contains(";") && triggerDepth==0 && stringDepth==0)
                    {
                        bool skipQuery = false;
                        if(queryFromParts.contains("CREATE TABLE sqlite_sequence"))
                            skipQuery=true;

                        if(queryFromParts.trimmed().isEmpty())
                            skipQuery=true;

                        if(queryFromParts.trimmed()==";")
                            skipQuery=true;

                        if(!skipQuery)
                        {
                            if (!query.exec(queryFromParts))
                            {
                                qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                                return 1;
                            }
                           // qDebug()<<queryFromParts;
                        }
                        queryFromParts.clear();
                    }

                }

                QDialog dlg;
                QFormLayout layout;
                dlg.setLayout(&layout);

                QLineEdit posID;
                layout.addRow(_T("Код ПОС-а"), &posID);

                QLineEdit generatorMin;
                layout.addRow(_T("Генератор мин"), &generatorMin);

                QLineEdit generatorMax;
                layout.addRow(_T("Генератор макс"), &generatorMax);

                QPushButton bt;
                bt.setText("OK");
                layout.addRow(0, &bt);
                dlg.connect(&bt, SIGNAL(clicked()), &dlg, SLOT(accept()));

                if(dlg.exec()==QDialog::Accepted)
                {
                    query.prepare(settings->value(_S("global/queries/set_pos_id")).toString());
                    query.bindValue(":val", posID.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }
                    query.prepare(settings->value(_S("global/queries/set_generator_min")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_min1_sqlite")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_min2_sqlite")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_max")).toString());
                    query.bindValue(":val", generatorMax.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                }
                else
                {
                    QMessageBox message;
                    message.setText(_T("Создание новой базы данных отменено"));
                    message.exec();
                    return 1;
                }

               solved = true;
            }
        }

        if(!solved){
            qCritical() << _T("%1 Ошибка чтения настроек\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
            return 1;
        }
    }


    int width  = 0;
    int height = 0;

    if (QApplication::desktop()->screenGeometry().width() > QApplication::desktop()->screenGeometry().height())
    {
        width  = QApplication::desktop()->screenGeometry().width();
        height = QApplication::desktop()->screenGeometry().height();
    }
    else
    {
        width  = QApplication::desktop()->screenGeometry().height();
        height = QApplication::desktop()->screenGeometry().width();
    }


    double scale = settings->value("global/button_scale", 1).toDouble();



    vars->insert(_S("standart_button_width"), (int) width / 12 * scale);
    vars->insert(_S("standart_button_height"), (int) height / 12 * scale);
    vars->insert(_S("standart_text_height"), (int) height / 18 * scale);
    vars->insert(_S("standart_margins"), (int) vars->value(_S("standart_button_width")).toInt() * 0.1 * scale);

    // заполняем тут, чтобы не тянуть в плагины все файлы
    data->setPrinter(new ChequePrinter(data->getSettings(), data->getVariables()));


    if (loglevel > 0)
    {
        QStringList keys = settings->allKeys();
        for (int i = 0; i < keys.count(); i++)
            qDebug() << _T("%1 Настройки: %2 %3").arg(posForLog).arg(keys.at(i)).arg(settings->value(keys.at(i)).toString());
    }


    if (loglevel > 0)
        qDebug() << _T("%1 Запуск ").arg(posForLog);


    MainWindow window(data);
    window.showFullScreen();

    // проверка 3
    return a.exec();
}
コード例 #10
0
void Fenetre::changeAttributSommetGraphe(GrapheColore* graph)
{
    vector<SommetColore*> listeSommets=graph->getListeSommets();
    //Création d'une boîte de dialogue
    QDialog fenDiag;

    //Boutons OK et Annuler
    QHBoxLayout *layoutButton=new QHBoxLayout;
    QPushButton *okFenDiag=new QPushButton("&OK");
    QPushButton *cancFenDiag=new QPushButton("&Annuler");
    layoutButton->addWidget(okFenDiag);
    layoutButton->addWidget(cancFenDiag);

    connect(okFenDiag, SIGNAL(clicked()), &fenDiag, SLOT(accept()));
    connect(cancFenDiag, SIGNAL(clicked()), &fenDiag, SLOT(reject()));

    //Création de la liste des sommets
    QComboBox *boxSommets=new QComboBox;
    for (int i = 0 ; i < listeSommets.size(); i++){
        boxSommets->addItem(listeSommets[i]->getNom());
    }

    //Ajout de tout ça à la fenêtre de dialogue
    QVBoxLayout *layoutFenetre=new QVBoxLayout;
    layoutFenetre->addWidget(boxSommets);
    layoutFenetre->addLayout(layoutButton);
    fenDiag.setLayout(layoutFenetre);

    //On affiche la fenêtre
    fenDiag.setVisible(true);
    fenDiag.setModal(true);

    //On traîte la demande
    if(fenDiag.exec()){ //Si on a cliqué sur ok !
        int currentIndex=boxSommets->currentIndex();
        SommetColore *sommetModif=listeSommets[currentIndex];

        //On demande ce qu'on veut modifier à ce sommet
        QDialog fenDiag2;

        //On réutilise les mêmes boutons qu'avant
        disconnect(okFenDiag, SIGNAL(clicked()), &fenDiag, SLOT(accept()));
        disconnect(cancFenDiag, SIGNAL(clicked()), &fenDiag, SLOT(reject()));
        connect(okFenDiag, SIGNAL(clicked()), &fenDiag2, SLOT(accept()));
        connect(cancFenDiag, SIGNAL(clicked()), &fenDiag2, SLOT(reject()));

        QComboBox *boxOptions=new QComboBox;
        QStringList options;
        options<<"Modifier le nom du sommet"<<"Modifier la forme du sommet"<<"Modifier la couleur du sommet";
        boxOptions->addItems(options);

        QVBoxLayout *layoutFenetre2=new QVBoxLayout;
        layoutFenetre->removeItem(layoutButton);
        layoutFenetre2->addWidget(boxOptions);
        layoutFenetre2->addLayout(layoutButton);

        fenDiag2.setLayout(layoutFenetre2);
        fenDiag2.setVisible(true);
        fenDiag2.setModal(true);

        if(fenDiag2.exec()){
            switch(boxOptions->currentIndex()){
            case 0 : {
                modifSommetNom(sommetModif);
                graph->notifyArete(sommetModif);
                redessinerComboArc();
                break;
            } case 1 : {
                modifSommetForme(sommetModif);
                break;
            } case 2 : {
                modifSommetCouleur(sommetModif);
                break;
            }
            }
        }
    }
}
コード例 #11
0
void TopicPublisherROS::filterDialog(bool)
{   
    auto all_topics = RosIntrospectionFactory::get().getTopicList();

    if( all_topics.empty() ) return;

    QDialog* dialog = new QDialog();
    dialog->setWindowTitle("Select topics to be published");
    dialog->setMinimumWidth(350);
    QVBoxLayout* vertical_layout = new QVBoxLayout();
    QFormLayout* grid_layout = new QFormLayout();

    std::map<std::string, QCheckBox*> checkbox;

    QFrame* frame = new QFrame;

    auto publish_sim_time  = new QRadioButton("Keep original timestamp and publish [/clock]");
    auto publish_real_time = new QRadioButton("Overwrite timestamp [std_msgs/Header/stamp]");
    QPushButton* select_button = new QPushButton("Select all");
    QPushButton* deselect_button = new QPushButton("Deselect all");

    publish_sim_time->setChecked( _publish_clock );
    publish_sim_time->setFocusPolicy(Qt::NoFocus);
    publish_sim_time->setToolTip("Publish the topic [/clock].\n"
                                 "You might want to set rosparam use_sim_time = true" );

    publish_real_time->setChecked( !_publish_clock );
    publish_real_time->setFocusPolicy(Qt::NoFocus);
    publish_real_time->setToolTip("Pretend it is a new message.\n"
                                 "The timestamp of the original message will be overwritten"
                                 "with ros::Time::Now()");

    select_button->setFocusPolicy(Qt::NoFocus);
    deselect_button->setFocusPolicy(Qt::NoFocus);

    for (const auto& topic: all_topics)
    {
        auto cb = new QCheckBox(dialog);
        auto filter_it = _topics_to_publish.find( *topic );
        if( filter_it == _topics_to_publish.end() )
        {
            cb->setChecked( true );
        }
        else{
            cb->setChecked( filter_it->second );
        }
        cb->setFocusPolicy(Qt::NoFocus);
        grid_layout->addRow( new QLabel( QString::fromStdString(*topic)), cb);
        checkbox.insert( std::make_pair(*topic, cb) );
        connect( select_button,   &QPushButton::pressed, [cb](){ cb->setChecked(true);} );
        connect( deselect_button, &QPushButton::pressed, [cb](){ cb->setChecked(false);} );
    }

    frame->setLayout(grid_layout);

    QScrollArea* scrollArea = new QScrollArea;
    scrollArea->setWidget(frame);

    QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);

    QHBoxLayout* select_buttons_layout = new QHBoxLayout;
    select_buttons_layout->addWidget( select_button );
    select_buttons_layout->addWidget( deselect_button );

    vertical_layout->addWidget( publish_sim_time );
    vertical_layout->addWidget( publish_real_time );
    vertical_layout->addWidget(scrollArea);
    vertical_layout->addLayout(select_buttons_layout);
    vertical_layout->addWidget( buttons );

    connect(buttons, SIGNAL(accepted()), dialog, SLOT(accept()));
    connect(buttons, SIGNAL(rejected()), dialog, SLOT(reject()));

    dialog->setLayout(vertical_layout);
    auto result = dialog->exec();

    if(result == QDialog::Accepted)
    {
        _topics_to_publish.clear();
        for(const auto& it: checkbox )
        {
            _topics_to_publish.insert( {it.first, it.second->isChecked() } );
        }

        //remove already created publisher if not needed anymore
        for (auto it = _publishers.begin(); it != _publishers.end(); /* no increment */)
        {
            const std::string& topic_name = it->first;
            if( !toPublish(topic_name) )
            {
                it = _publishers.erase(it);
            }
            else{
                it++;
            }
        }

        _publish_clock = publish_sim_time->isChecked();

        if( _publish_clock )
        {
            _clock_publisher = _node->advertise<rosgraph_msgs::Clock>( "/clock", 10, true);
        }
        else{
            _clock_publisher.shutdown();
        }

        QSettings settings;
        settings.setValue( "TopicPublisherROS/publish_clock", _publish_clock );
    }
}
コード例 #12
0
ファイル: ActionZone.cpp プロジェクト: vhotspur/otterdict
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();
}
コード例 #13
0
void QtIMAccountSettings::createIMProtocolWidget(QWidget* parent, QtEnumIMProtocol::IMProtocol imProtocol) 
{
	QDialog * imAccountTemplateWindow = new QDialog(parent);

	_ui = new Ui::IMAccountTemplate();
	_ui->setupUi(imAccountTemplateWindow);

	switch (imProtocol) {
	case QtEnumIMProtocol::IMProtocolMSN: {
		_imAccountPlugin = new QtMSNSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}
	case QtEnumIMProtocol::IMProtocolMYSPACE: {
		_imAccountPlugin = new QtMySpaceSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

	case QtEnumIMProtocol::IMProtocolFacebook: {
		_imAccountPlugin = new QtFacebookSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

   	case QtEnumIMProtocol::IMProtocolTwitter: {
		_imAccountPlugin = new QtTwitterSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

    case QtEnumIMProtocol::IMProtocolSkype: {
		_imAccountPlugin = new QtSkypeSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

	case QtEnumIMProtocol::IMProtocolYahoo: {
		_imAccountPlugin = new QtYahooSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

	case QtEnumIMProtocol::IMProtocolAIM: {
		_imAccountPlugin = new QtAIMSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

	case QtEnumIMProtocol::IMProtocolICQ: {
		_imAccountPlugin = new QtICQSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

	case QtEnumIMProtocol::IMProtocolJabber: {
		_imAccountPlugin = new QtJabberSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

	case QtEnumIMProtocol::IMProtocolGoogleTalk: {
		_imAccountPlugin = new QtGoogleTalkSettings(_userProfile, _imAccount, imAccountTemplateWindow);
		break;
	}

	case QtEnumIMProtocol::IMProtocolVoxOx:
		assert(false);								//VOXOX - JRT - 2009.07.01 - if we got here, then some one changed QtEnumIMProtocol.
		break;

	default:
		LOG_FATAL("unknown IM protocol=" + String::fromNumber(imProtocol));
	}

	SAFE_CONNECT_RECEIVER(_ui->saveButton,   SIGNAL(clicked()), _imAccountPlugin,		 SLOT(checkAndSave()));
	SAFE_CONNECT_RECEIVER(_ui->cancelButton, SIGNAL(clicked()), imAccountTemplateWindow, SLOT(reject()));

	QWidget * imProtocolWidget = _imAccountPlugin->getWidget();
	QString styleSheet("QLabel,QCheckBox{color:#343434;}");
	imProtocolWidget->setStyleSheet(styleSheet);
	Widget::createLayout(_ui->settingsGroupBox)->addWidget(imProtocolWidget);
	_ui->settingsGroupBox->setTitle(imProtocolWidget->windowTitle());

	imAccountTemplateWindow->setWindowTitle(imProtocolWidget->windowTitle());
	imAccountTemplateWindow->exec();
}
コード例 #14
0
void SvgCanvas::actionExport_to_callback()
{
	QDialog dialog;
	ExportToDialog export_to_dialog;
	export_to_dialog.setupUi(&dialog);
	QListWidget *list = export_to_dialog.formats_listWidget;
	QListWidgetItem *item;
	//Pixmaps formats
	QList<QByteArray> formats=QImageWriter::supportedImageFormats();
	for(int i=0;i<formats.size();i++)
	{
		QString text(formats[i]);
		item=new QListWidgetItem(text,list);
		item->setData(1,QVariant(PIXMAP));
	}
	//Vector formats
	formats= QPicture::outputFormats();
	for(int i=0;i<formats.size();i++)
	{
		QString text(formats[i]);
		item=new QListWidgetItem(text,list);
		item->setData(1,QVariant(PICTURE));
	}
	
	item=new QListWidgetItem("ps",list);
	item->setData(1,QVariant(PRINTER));
	
	item=new QListWidgetItem("pdf",list);
	item->setData(1,QVariant(PDF));
	
	item=new QListWidgetItem("svg",list);
	item->setData(1,QVariant(SVG));
	
	int ok=dialog.exec();
	if(ok==QDialog::Rejected) return;
	
	item =list->currentItem();
	int format=item->data(1).toInt();
	
	QPainter plot;
	switch(format)
	{
		case PIXMAP:
		{
			bool ok;
			int h, w = QInputDialog::getInteger(this, tr("Width"), tr("Width:"), 300, 0, 2147483647, 1, &ok);
			if(!ok) return;
			h=QInputDialog::getInteger(this, tr("Height"), tr("Height:"), 200, 0, 2147483647, 1, &ok);
			if(!ok) return;
			QString s = QFileDialog::getSaveFileName(this, "Choose a filename to save");
			if(s.isEmpty()) return;
			QImage image(w,h,QImage::Format_RGB32);
			plot.begin(&image);
			svg_plot->renderer()->render(&plot);
			plot.end();
			image.save(s,item->data(0).toString().toLocal8Bit().data());
		}
		break;
		case PICTURE:
		{
			bool ok;
			int h, w = QInputDialog::getInteger(this, tr("Width"), tr("Width:"), 300, 0, 2147483647, 1, &ok);
			if(!ok) return;
			h=QInputDialog::getInteger(this, tr("Height"), tr("Height:"), 200, 0, 2147483647, 1, &ok);
			if(!ok) return;
			QString s = QFileDialog::getSaveFileName(this, "Choose a filename to save");
			if(s.isEmpty()) return;
			QPicture image;
			const QRect r(0,0,w,h);
			image.setBoundingRect(r);
			plot.begin(&image);
			svg_plot->renderer()->render(&plot);
			plot.end();
			image.save(s,item->data(0).toString().toLocal8Bit().data());
		}
		break;
		case PRINTER:
		{
			QPrinter p;
			QPrintDialog printDialog(&p, this);
			if (printDialog.exec() != QDialog::Accepted) return;
			plot.begin(&p);
			svg_plot->renderer()->render(&plot);
			plot.end();
		}
		break;
		case PDF:
		{
			QPrinter p;
			QPrintDialog printDialog(&p, this);
			p.setOutputFormat(QPrinter::PdfFormat);
			if (printDialog.exec() != QDialog::Accepted) return;
			
			plot.begin(&p);
			svg_plot->renderer()->render(&plot);
			plot.end();
		}
		break;
		case SVG:
		{
			QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("*.svg"));
			QSvgGenerator p;
			p.setFileName(fileName);
			plot.begin(&p);
			svg_plot->renderer()->render(&plot);
			plot.end();
		}
	}
}
コード例 #15
0
ファイル: port.cpp プロジェクト: dancollins/ostinato
bool Port::openStreams(QString fileName, bool append, QString &error)
{
    bool ret = false; 
    QDialog *optDialog;
    QProgressDialog progress("Opening Streams", "Cancel", 0, 0, mainWindow);
    OstProto::StreamConfigList streams;
    AbstractFileFormat *fmt = AbstractFileFormat::fileFormatFromFile(fileName);

    if (fmt == NULL)
        goto _fail;

    if ((optDialog = fmt->openOptionsDialog()))
    {
        int ret;
        optDialog->setParent(mainWindow, Qt::Dialog);
        ret = optDialog->exec();
        optDialog->setParent(0, Qt::Dialog);
        if (ret == QDialog::Rejected)
            goto _user_opt_cancel;
    }

    progress.setAutoReset(false);
    progress.setAutoClose(false);
    progress.setMinimumDuration(0);
    progress.show();

    mainWindow->setDisabled(true);
    progress.setEnabled(true); // to override the mainWindow disable

    connect(fmt, SIGNAL(status(QString)),&progress,SLOT(setLabelText(QString)));
    connect(fmt, SIGNAL(target(int)), &progress, SLOT(setMaximum(int)));
    connect(fmt, SIGNAL(progress(int)), &progress, SLOT(setValue(int)));
    connect(&progress, SIGNAL(canceled()), fmt, SLOT(cancel()));

    fmt->openStreamsOffline(fileName, streams, error);
    qDebug("after open offline");

    while (!fmt->isFinished())
        qApp->processEvents();
    qDebug("wait over for offline operation");

    if (!fmt->result())
        goto _fail;
    
    // process any remaining events posted from the thread
    for (int i = 0; i < 10; i++)
        qApp->processEvents();

    if (!append)
    {
        int n = numStreams();

        progress.setLabelText("Deleting existing streams...");
        progress.setRange(0, n);
        for (int i = 0; i < n; i++)
        {
            if (progress.wasCanceled())
                goto _user_cancel;
            deleteStreamAt(0);
            progress.setValue(i);
            if (i % 32 == 0)
                qApp->processEvents();
        }
    }

    progress.setLabelText("Constructing new streams...");
    progress.setRange(0, streams.stream_size());
    for (int i = 0; i < streams.stream_size(); i++)
    {
        if (progress.wasCanceled())
            goto _user_cancel;
        newStreamAt(mStreams.size(), &streams.stream(i));
        progress.setValue(i);
        if (i % 32 == 0)
            qApp->processEvents();
    }

_user_cancel:
    emit streamListChanged(mPortGroupId, mPortId);
_user_opt_cancel:
    ret = true;

_fail:
    progress.close();
    mainWindow->setEnabled(true);
    recalculateAverageRates();
    return ret;
}
コード例 #16
0
void ImageComparator::Compare( QString const&filepath, QImage const &img )
{
  QSettings sett(SettingsValues::filename(),QSettings::IniFormat);
  sett.beginGroup(SettingsValues::comparatorGroupName());
  QString goldenPath = sett.value(SettingsValues::goldenPathValueName(), SettingsValues::goldenPathDefault()).toString() + "/";
  QString diffPath =  sett.value(SettingsValues::diffPathValueName(), SettingsValues::diffPathDefault()).toString() + "/";  
  sett.endGroup();
  QFileInfo info(filepath);
  QString const samplePath = goldenPath + info.fileName();
  if(!QFile::exists(samplePath))
  {
    QMessageBox::critical(NULL, "Error!", QString("Golden image \"%1\" does not exist!").arg(samplePath));
    return;
  }
  QImage sample(samplePath);
  sample = sample.convertToFormat(QImage::Format_ARGB32_Premultiplied);
  if(sample.isNull())
  {
    QMessageBox::critical(NULL, "Error!", QString("Could not open file \"%1\"!").arg(samplePath));
    return;
  }
  if(sample.size() != img.size())
  {
    QMessageBox::critical(NULL, "Error!", QString("Sample and current images have different sizes!"));
    return;
  }
  unsigned long long accum = 0;
  int sx = sample.width();
  int sy = sample.height();
  int bpl = sample.bytesPerLine();
  QImage diffImg(sample.size(), QImage::Format_ARGB32);
  for (int y = 0; y < sy; ++y) {
    for (int x = 0; x < sx; ++x) 
    {
      for (int c = 0; c < 3; ++c) 
      {
        unsigned idx = y * bpl + (x << 2) + c;
        uchar diff = abs((int)sample.constBits()[idx] - (int)img.constBits()[idx]);
        diffImg.bits()[idx] = diff;
        accum += diff;
      }
      diffImg.bits()[y * bpl + (x << 2) + 3] = sample.bits()[y * bpl + (x << 2) + 3];
    }
  }
  QString const diffName = diffPath + info.fileName();
  QDir diffDir(diffPath);
  if(!diffDir.exists(diffPath))
  {
    if(!QDir(diffPath + "/..").mkpath(diffDir.dirName()))
    {
      QMessageBox::critical(NULL, "Error!", QString("Could not create diff folder \"%1\"!").arg(diffPath));
      return;
    }
  }
  if(!diffImg.save(diffName, info.suffix().toAscii().data()))
  {
    QMessageBox::critical(NULL, "Error!", QString("Could not save the difference image \"%1\"!").arg(diffName));
    return;
  }
  double diff = ((double)accum / (img.size().width() * img.size().height() * 3) * 100.0 / 255.0);

  QDialog dlg;
  Ui::ImgDifferenceDialog ui;
  ui.setupUi(&dlg);
  dlg.setModal(true);
  dlg.setSizeGripEnabled(false);
  dlg.layout()->setSizeConstraint( QLayout::SetFixedSize );
  ui.label->setText(QString("The difference is: %1").arg(diff, 0, 'f', 2));
  QPixmap pxmp = QPixmap::fromImage(diffImg);
  QRect r = ui.frame->frameRect();
  if(r.width() < pxmp.width())
    pxmp = pxmp.scaledToWidth(r.width(), Qt::SmoothTransformation);
  if(r.height() < pxmp.height())
    pxmp = pxmp.scaledToHeight(r.height(), Qt::SmoothTransformation);
  //ui.differenceLabel->resize(pxmp.size());
  ui.differenceLabel->setPixmap(pxmp);
  
  dlg.exec();

}
コード例 #17
0
ファイル: LaunchPad.cpp プロジェクト: loh-tar/filu
void  LaunchPad::buttonContextMenu(const QPoint& /*pos*/)
{
  QAbstractButton* btn = static_cast<QAbstractButton*>(sender());
  int id = mButtons.id(btn);

  QDialog      dialog;
  QGridLayout  layout(&dialog);
  QLabel*      label;
  int          row = 0;            // Count layout rows

  label = new QLabel(tr("Name"));
  label->setAlignment(Qt::AlignRight);
  layout.addWidget(label, row, 0);
  QLineEdit name(btn->text());
  name.setToolTip(tr("Button caption"));
  layout.addWidget(&name, row++, 1);
  layout.setColumnStretch(1, 1);

  label = new QLabel(tr("Tip"));
  label->setAlignment(Qt::AlignRight);
  layout.addWidget(label, row, 0);
  QLineEdit tip(btn->toolTip());
  tip.setToolTip(tr("Button tool tip"));
  tip.setCursorPosition(0);
  layout.addWidget(&tip, row++, 1, 1, 2);
  layout.setColumnStretch(2, 3);

  label = new QLabel(tr("Command"));
  label->setAlignment(Qt::AlignRight);
  layout.addWidget(label, row, 0);
  QLineEdit command(mCommands.at(id));
  //QTextEdit command(mCommands.at(id));
  command.setCursorPosition(0);
  command.setToolTip(tr("Available Tags are: %1").arg("[Provider] [Symbol] [Market] "
                                                      "[FiId] [MarketId]"));
  layout.addWidget(&command, row++, 1, 1, 2); // Spawn over two colums...
//   layout.setColumnStretch(2, 2);              // ...and take more space

  label = new QLabel(tr("Symbol Type"));
  label->setAlignment(Qt::AlignRight);
  layout.addWidget(label, row, 0);
//   QLineEdit symbolType(mSymbolTypes.at(id));
  QComboBox symbolType;
  symbolType.setToolTip(tr("Witch type has to be [Symbol]. When empty is called once with any symbol\n"
                           "(You should not use [Symbol] in this case at the command)"));
  SymbolTypeTuple* st = mFilu->getSymbolTypes(Filu::eAllTypes);
  if(st)
  {
    while(st->next()) symbolType.addItem(st->caption());
  }

  symbolType.addItem("");
  symbolType.setCurrentIndex(symbolType.findText(mSymbolTypes.at(id)));

  layout.addWidget(&symbolType, row, 1);

  QCheckBox allMarkets(tr("All Markets"));
  allMarkets.setToolTip(tr("Call multiple times with all markets by 'Symbol Type'"));
  allMarkets.setChecked(mMultis.at(id));
  layout.addWidget(&allMarkets, row++, 2);

  // Add an empty row to take unused space
  layout.addWidget(new QWidget, row, 1);
  layout.setRowStretch(row++, 2);

  // Build the button line
  QDialogButtonBox dlgBtns(QDialogButtonBox::Save | QDialogButtonBox::Discard);
  QPushButton* db = dlgBtns.button(QDialogButtonBox::Discard);
  dlgBtns.addButton(db, QDialogButtonBox::RejectRole);
  connect(&dlgBtns, SIGNAL(accepted()), &dialog, SLOT(accept()));
  connect(&dlgBtns, SIGNAL(rejected()), &dialog, SLOT(reject()));

  DialogButton* remove = new DialogButton(tr("&Remove"), -1);
  remove->setToolTip(tr("Remove button"));
  dlgBtns.addButton(remove, QDialogButtonBox::ActionRole);
  connect(remove, SIGNAL(clicked(int)), &dialog, SLOT(done(int)));

  DialogButton* add = new DialogButton(tr("&Add"), 2);
  add->setToolTip(tr("Copy to new button"));
  dlgBtns.addButton(add, QDialogButtonBox::ActionRole);
  connect(add, SIGNAL(clicked(int)), &dialog, SLOT(done(int)));

  layout.addWidget(&dlgBtns, row, 1, 1, 2);

  dialog.setWindowTitle(tr("LaunchPad - Edit button '%1'").arg(btn->text()));
  dialog.setMinimumWidth(350);

  switch (dialog.exec())
  {
    case 0:     // Discard
      return;
      break;
    case -1:    // Remove
    {
      int ret = QMessageBox::warning(&dialog
                  , tr("LaunchPad - Last chance to keep your data")
                  , tr("Are you sure to delete button <b>'%1'</b> with all your work<b>?</b>")
                      .arg(btn->text())
                  , QMessageBox::Yes | QMessageBox::No
                  , QMessageBox::No);

      if(ret == QMessageBox::No) return;

      deleteButton(btn);

      mCommands.removeAt(id);
      mSymbolTypes.removeAt(id);
      mMultis.removeAt(id);
      break;
    }
    case  1:    // Save
      setButtonName(btn, name.text());
      btn->setToolTip(tip.text());

      mCommands[id] = command.text();
      //mCommands[id] = command.toPlainText();
//       mSymbolTypes[id] = symbolType.text();
      mSymbolTypes[id] = symbolType.currentText();
      mMultis[id] = allMarkets.isChecked();
      break;
    case  2:    // Add
      btn = newButton(name.text());
      btn->setToolTip(tip.text());

      mCommands.append(command.text());
      //mCommands.append(command.toPlainText());
//       mSymbolTypes.append(symbolType.text());
      mSymbolTypes.append(symbolType.currentText());
      mMultis.append(allMarkets.isChecked());
      mButtons.setId(btn, mCommands.size() - 1);
      break;
  }

  saveSettings();
}
コード例 #18
0
ファイル: mainwindow.cpp プロジェクト: f0ma/hardwareexpert
void MainWindow::callOptionDialog (QVector<ConsoleInterface::optionDialogEntry> * options,bool * ret)
{
if (options->isEmpty()) return;

QVectorIterator<ConsoleInterface::optionDialogEntry> it(*options);

QDialog * d = new QDialog(this);

d->setModal(true);

QVBoxLayout * dbl = new QVBoxLayout();
d->setLayout(dbl);

QList <QWidget * > ents;

QHBoxLayout * sl;
QLabel * l;
QLineEdit * lew;
QCheckBox * chw;
QComboBox * cbl;

for(int i=0;i< (*options).size();i++)
{
sl = new QHBoxLayout();
l = new QLabel(d);
l->setText(it.next().text);
sl->addWidget(l);

if((*options)[i].type == ConsoleInterface::OPT_DEC)
{
    lew = new QLineEdit(d);
    lew->setValidator(new QIntValidator( d ));
    QString s;
    s.setNum((*options)[i].valueInt);
    lew->setText(s);
    sl->addWidget(lew);
    ents.append(lew);
}

if((*options)[i].type == ConsoleInterface::OPT_HEX)
{
    lew = new QLineEdit(d);
    lew->setValidator(new QRegExpValidator(QRegExp("([A-Fa-f0-9][A-Fa-f0-9])+"),d));
    QString s;
    s.setNum((*options)[i].valueInt,16);
    lew->setText(s);
    sl->addWidget(lew);
    ents.append(lew);
}

if((*options)[i].type == ConsoleInterface::OPT_STR)
{
    lew = new QLineEdit(d);
    lew->setValidator(NULL);
    QString s = (*options)[i].valueStr;
    lew->setText(s);
    sl->addWidget(lew);
    ents.append(lew);
}


if((*options)[i].type == ConsoleInterface::OPT_CHK)
{
    chw = new QCheckBox(d);
    chw->setChecked((*options)[i].valueInt == 0 ? false : true);
    sl->addWidget(chw);
    ents.append(chw);
}


if((*options)[i].type == ConsoleInterface::OPT_LIST)
{
cbl = new QComboBox(d);
cbl->addItems((*options)[i].variants);
sl->addWidget(cbl);
ents.append(cbl);
}




dbl->addLayout(sl);


}


QHBoxLayout * hbl = new QHBoxLayout(d);

QPushButton * obOK = new QPushButton(tr("OK"),d);
QPushButton * obCancel = new QPushButton(tr("Cancel"),d);
QPushButton * obAbort = new QPushButton(tr("Abort"),d);

connect(obOK,SIGNAL(clicked()),d,SLOT(accept()));
connect(obCancel,SIGNAL(clicked()),d,SLOT(reject()));
connect(obAbort,SIGNAL(clicked()),d,SLOT(reject()));
connect(obAbort,SIGNAL(clicked()),this,SLOT(on_stopButton_clicked()),Qt::QueuedConnection);

hbl->addStretch(10);
hbl->addWidget(obOK);
hbl->addWidget(obCancel);
hbl->addWidget(obAbort);

dbl->addLayout(hbl);


if(d->exec()==QDialog::Accepted)
{

    for(int i=0;i< (*options).size();i++)
    {
        if((*options)[i].type == ConsoleInterface::OPT_DEC)
        {
            (*options)[i].valueInt  = dynamic_cast<QLineEdit*>(ents[i])->text().toInt();
        }

        if((*options)[i].type == ConsoleInterface::OPT_HEX)
        {
            (*options)[i].valueInt  = dynamic_cast<QLineEdit*>(ents[i])->text().toInt(0,16);
        }

        if((*options)[i].type == ConsoleInterface::OPT_STR)
        {
            QString t =  dynamic_cast<QLineEdit*>(ents[i])->text();
            (*options)[i].valueStr  = t;
        }


        if((*options)[i].type == ConsoleInterface::OPT_CHK)
        {
            (*options)[i].valueInt  = dynamic_cast<QCheckBox*>(ents[i])->isChecked();
        }


        if((*options)[i].type == ConsoleInterface::OPT_LIST)
        {
            (*options)[i].valueInt  = dynamic_cast<QComboBox*>(ents[i])->currentIndex();
        }
    }

*ret =true;
}
else
{
*ret =false;
}



delete d;
}
コード例 #19
0
ファイル: mainwindow.cpp プロジェクト: radekp/qneoroid
void MainWindow::addHighscore(int score)
{
  QDialog* dialog = new QDialog(this);
  dialog->setWindowTitle(tr("Highscores"));

  QGridLayout* grid = new QGridLayout(dialog);
  grid->setColumnStretch(2, 1);
  grid->setRowStretch(NumHighscores + 3, 1);
  grid->setHorizontalSpacing(40);

  QLabel* label = new QLabel(dialog);
  label->setPixmap(QPixmap(":/computer2.png"));
  grid->addWidget(label, 0, 0, 2, 0);
  label = new QLabel(tr("<h3>Highscores"), dialog);
  grid->addWidget(label, 0, 1, 1, 3);

  const QString header = (skill == Novice) ? tr("Novices") :
    (skill == Normal) ? tr("Amateurs") :
      (skill == Expert) ? tr("Experts") : tr("Masters");

  grid->addWidget(new QLabel("<b>#", dialog), 1, 1);
  grid->addWidget(new QLabel("<b>" + header, dialog), 1, 2);
  grid->addWidget(new QLabel(tr("<b>Scores"), dialog), 1, 3);

  QFrame* frame = new QFrame(dialog);
  frame->setFrameStyle(QFrame::HLine | QFrame::Sunken);
  grid->addWidget(frame, 2, 1, 1, 3);

  QLineEdit* line = 0;
  QStringList::Iterator inserted;
  QStringList::Iterator it = highscores.begin()+(2 * skill * NumHighscores);
  for(unsigned int i = 0; i < NumHighscores; i++)
  {
    label = new QLabel(QString::number(i + 1), dialog);
    grid->addWidget(label, i + 3, 1);

    QStringList::Iterator next = it;
    if(score > 0 && score <= (*(++next)).toInt() && !line)
    {
      inserted = it;
      line = new QLineEdit(username, dialog);
      grid->addWidget(line, i + 3, 2);
      label = new QLabel(QString::number(score), dialog);
      grid->addWidget(label, i + 3, 3);
    }
    else
    {
      grid->addWidget(new QLabel(*(it++), dialog), i + 3, 2);
      grid->addWidget(new QLabel(*(it++), dialog), i + 3, 3);
    }
  }
  QPushButton* button = new QPushButton("OK", dialog);
  connect(button, SIGNAL(clicked()), dialog, SLOT(accept()));
  const int pos = NumHighscores + 4;
  grid->addWidget(button, pos, 1, pos, 3, Qt::AlignHCenter);

  dialog->exec();
  if(line)
  {
    username = line->text();
    *inserted = username;
    *(++inserted) = QString::number(score);
  }
  delete dialog;
}
コード例 #20
0
ファイル: ClassResultOp.cpp プロジェクト: eramox/eiimage
void ClassResultOp::operator()(const imagein::Image* img, const std::map<const imagein::Image*, std::string>&) {

    QDialog* dialog = new QDialog(QApplication::activeWindow());
    QVBoxLayout* layout = new QVBoxLayout(dialog);
    QFormLayout* formLayout = new QFormLayout();
    QSpinBox* innerBox = new QSpinBox();
    QSpinBox* borderBox = new QSpinBox();
    innerBox->setRange(0, img->getWidth());
    borderBox->setRange(0, img->getWidth());
    innerBox->setSuffix(" px");
    borderBox->setSuffix(" px");
    innerBox->setValue(8);
    borderBox->setValue(2);
    formLayout->insertRow(0, qApp->translate("ClassResult", "Critère de zone intérieure : "), innerBox);
    formLayout->insertRow(1, qApp->translate("ClassResult", "Critère de zone frontière : "), borderBox);
    layout->addWidget(new QLabel(qApp->translate("ClassResult", "<b>Critère de zones (relatifs aux zones totales) : </b>")));
    layout->addLayout(formLayout);
    layout->addWidget(new QLabel(qApp->translate("ClassResult", "<b>Select the image's classes zones : </b>")));
    ImageZoneSelector* zoneSelector = new ImageZoneSelector(dialog, img);
    layout->addWidget(zoneSelector);
    QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, Qt::Horizontal, dialog);
    layout->addWidget(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;

    string returnval;

    int param1 = 2;
    int param2 = 8;
    vector<Rectangle> selection = zoneSelector->getSelections();
    int K = selection.size();
    int* classes = new int[K];
    outText(qApp->translate("ClassResult", "Voici les résultats du classement : \n").toStdString());
    outText(qApp->translate("ClassResult", "\nNombre de classes = %1 ").arg(K).toStdString());
    for(int i = 0; i < K; ++i) {
        Histogram histo = img->getHistogram(0, selection.at(i));
        classes[i] = (uint8_t) (std::max_element(histo.begin(), histo.end()) - histo.begin());
        outText(qApp->translate("ClassResult", "Valeur de la classe %1 = %2").arg(i+1).arg(classes[i]).toStdString());
    }


    //Zone frontire
    double *tauxF = new double[K];
    double *tauxI = new double[K];
    for(int i = 0; i < K; ++i){
        tauxF[i] = 0.;
        tauxI[i] = 0.;
    }

    for(int n = 0; n < K; ++n) {
        Rectangle zone = selection.at(n);
        for(unsigned int j = zone.top(); j < zone.bottom(); ++j) {
            for(unsigned int i = zone.left(); i < zone.right(); ++i) {
                if(img->getPixelAt(i, j) == classes[n]) {
                    if( i >= zone.left() + param2 && i < zone.right() - param2 && j >= zone.top() + param2 && j < zone.bottom() - param2 ) {
                        tauxI[n]++;
                    }
                    if( i < zone.left() + param1 || i >= zone.right() - param1 || j < zone.top() + param1 || j >= zone.bottom() - param1 ) {
                        tauxF[n]++;
                    }
                }
            }
        }
    }

    for(int n = 0; n < K; ++n) {
        Rectangle zone = selection.at(n);
        const double areaI = (zone.h - 2*param2) * (zone.w - 2*param2);
        const double areaF = (zone.h * zone.w) - (zone.h - 2*param1) * (zone.w - 2*param1);
        tauxI[n] = tauxI[n] * 100. / areaI;
        tauxF[n] = tauxF[n] * 100. / areaF;
    }
    for(int n = 0; n < K; ++n) {
        outText(qApp->translate("ClassResult", "Le taux de bon classement en zone intérieure %1 vaut: %2\%").arg(n+1).arg(tauxI[n], 0, 'f', 2).toStdString());
    }
    for(int n = 0; n < K; ++n) {
        outText(qApp->translate("ClassResult", "Le taux de bon classement en zone frontière %1 vaut: %2\%").arg(n+1).arg(tauxF[n], 0, 'f', 2).toStdString());
    }

    double tauxGI = 0., tauxGF = 0.;
    for(int i = 0; i < K; ++i){
        tauxGI += tauxI[i];
        tauxGF += tauxF[i];
    }
    tauxGI /= K;
    tauxGF /= K;

    outText(qApp->translate("ClassResult", "Le taux de bon classement en zone intérieure globale vaut: %1\%").arg(tauxGI, 0, 'f', 2).toStdString());
    outText(qApp->translate("ClassResult", "Le taux de bon classement en zone frontière globale vaut: %1\%").arg(tauxGF, 0, 'f', 2).toStdString());

    outText(returnval);
}
コード例 #21
0
ファイル: cash_reconcile.cpp プロジェクト: cwarden/quasar
void
CashReconcile::slotReconcile()
{
    if (_lines->selectedItem() == NULL) {
	QString message;
	if (_company.shiftMethod() == Company::BY_STATION) {
	    message = tr("A station must be picked");
	} else {
	    message = tr("An employee must be picked");
	}
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    Id station_id = stationId();
    Id employee_id = employeeId();
    Id store_id = _store->getId();
    Id safe_store_id = _safeStore->getId();
    Id safe_id = _safeId->getId();
    Id adjust_id = _adjust->getId();
    Id transfer_id = _transfer->getId();

    Id safe_station_id;
    Id safe_employee_id;
    if (_company.shiftMethod() == Company::BY_STATION)
	safe_station_id = safe_id;
    else
	safe_employee_id = safe_id;

    if (store_id == INVALID_ID) {
	QString message = tr("A store must be entered");
	QMessageBox::critical(this, tr("Error"), message);
	_store->setFocus();
	return;
    }
    if (safe_store_id == INVALID_ID) {
	QString message = tr("A safe store must be entered");
	QMessageBox::critical(this, tr("Error"), message);
	_tabs->showPage(_setup);
	_safeStore->setFocus();
	return;
    }
    if (safe_id == INVALID_ID) {
	QString message = tr("A safe must be entered");
	QMessageBox::critical(this, tr("Error"), message);
	_tabs->showPage(_setup);
	_safeId->setFocus();
	return;
    }
    if (adjust_id == INVALID_ID) {
	QString message = tr("An over/short account must be entered");
	QMessageBox::critical(this, tr("Error"), message);
	_tabs->showPage(_setup);
	_adjust->setFocus();
	return;
    }
    if (transfer_id == INVALID_ID) {
	QString message = tr("A transfer account must be entered");
	QMessageBox::critical(this, tr("Error"), message);
	_tabs->showPage(_setup);
	_transfer->setFocus();
	return;
    }
    if (_shifts.size() == 0) {
	QString message = tr("You must have at least one shift");
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    QDate date = _date->getDate();
    if (date.isNull()) {
	QString message = tr("The date to reconcile is required");
	QMessageBox::critical(this, tr("Error"), message);
	_date->setFocus();
	return;
    }

    // Posting time is current time if closing for today or 11:59:59 PM
    QTime time = QTime::currentTime();
    if (date != QDate::currentDate())
	time = QTime(23, 59, 59);

    vector<Shift> shifts = _shifts;
    vector<TenderCount> counts = _counts;

    if (shifts.size() > 1 || counts.size() > 1) {
	// TODO: ask which shifts/counts to use
    }

    QApplication::setOverrideCursor(waitCursor);
    qApp->processEvents();

    Id shift_id = shifts[0].id();
    _tenders.clear();
    _summary.clear();

    // Process shifts and add tenders to summary
    unsigned int i;
    for (i = 0; i < shifts.size(); ++i) {
	const Shift& shift = shifts[i];

	GltxSelect conditions;
	conditions.shift_id = shift.id();
	conditions.activeOnly = true;
	vector<Gltx> gltxs;
	_quasar->db()->select(gltxs, conditions);

	for (unsigned int j = 0; j < gltxs.size(); ++j) {
	    const Gltx& gltx = gltxs[j];

	    for (unsigned int k = 0; k < gltx.tenders().size(); ++k) {
		Id tender_id = gltx.tenders()[k].tender_id;
		fixed amount = gltx.tenders()[k].conv_amt;
		if (gltx.tenders()[k].voided) continue;

		addShiftAmt(tender_id, amount);
	    }
	}
    }

    // Process counts and add tenders to summary
    for (i = 0; i < counts.size(); ++i) {
	const TenderCount& count = counts[i];

	for (unsigned int j = 0; j < count.tenders().size(); ++j) {
	    const TenderInfo& info = count.tenders()[j];
	    addCountAmt(info.tender_id, info.amount);
	}
    }

    // Sort tenders by menu number
    std::sort(_summary.begin(), _summary.end());

    // Prepare over/short transaction
    TenderAdjust adjustment;
    adjustment.setPostDate(date);
    adjustment.setPostTime(time);
    adjustment.setMemo(tr("Over/Short"));
    adjustment.setStoreId(store_id);
    adjustment.setStationId(station_id);
    adjustment.setEmployeeId(employee_id);
    adjustment.setShiftId(shift_id);
    adjustment.setAccountId(adjust_id);

    // Prepare transfer out transaction
    TenderAdjust transOut;
    transOut.setPostDate(date);
    transOut.setPostTime(time);
    transOut.setMemo(tr("Deposit to safe"));
    transOut.setStoreId(store_id);
    transOut.setStationId(station_id);
    transOut.setEmployeeId(employee_id);
    transOut.setShiftId(shift_id);
    transOut.setAccountId(transfer_id);

    // Memo for transfer in depends on method
    QString memo;
    if (station_id != INVALID_ID) {
	Station station;
	_quasar->db()->lookup(station_id, station);
	memo = tr("Deposit from: %1").arg(station.name());
    } else {
	Employee employee;
	_quasar->db()->lookup(employee_id, employee);
	memo = tr("Deposit from: %1").arg(employee.nameFL());
    }

    // Prepare transfer in transaction
    TenderAdjust transIn;
    transIn.setPostDate(date);
    transIn.setPostTime(time);
    transIn.setMemo(memo);
    transIn.setStoreId(safe_store_id);
    transIn.setStationId(safe_station_id);
    transIn.setEmployeeId(safe_employee_id);
    transIn.setAccountId(transfer_id);

    // Setup screen
    QDialog* dialog = new QDialog(this, "Summary", true);
    dialog->setCaption(tr("Reconcile Summary"));

    ListView* tenderList = new ListView(dialog);
    tenderList->addTextColumn(tr("Tender"), 20);
    tenderList->addMoneyColumn(tr("Shifts"));
    tenderList->addMoneyColumn(tr("Counts"));
    tenderList->addMoneyColumn(tr("Over/Short"));
    tenderList->setAllColumnsShowFocus(true);
    tenderList->setSorting(-1);

    QFrame* buttons = new QFrame(dialog);
    QPushButton* post = new QPushButton(tr("Reconcile"), buttons);
    QPushButton* cancel = new QPushButton(tr("Cancel"), buttons);
    cancel->setDefault(true);

    connect(post, SIGNAL(clicked()), dialog, SLOT(accept()));
    connect(cancel, SIGNAL(clicked()), dialog, SLOT(reject()));

    QGridLayout* buttonGrid = new QGridLayout(buttons);
    buttonGrid->setSpacing(3);
    buttonGrid->setMargin(3);
    buttonGrid->setColStretch(0, 1);
    buttonGrid->addWidget(post, 0, 1);
    buttonGrid->addWidget(cancel, 0, 2);

    QGridLayout* grid = new QGridLayout(dialog);
    grid->setSpacing(3);
    grid->setMargin(3);
    grid->setRowStretch(0, 1);
    grid->setColStretch(0, 1);
    grid->addWidget(tenderList, 0, 0);
    grid->addWidget(buttons, 1, 0);

    // Process summary info
    fixed shiftsTotal = 0.0;
    fixed countsTotal = 0.0;
    fixed overShort = 0.0;
    fixed transferAmt = 0.0;
    ListViewItem* last = NULL;
    for (i = 0; i < _summary.size(); ++i) {
	const Tender& tender = _summary[i].tender;
	fixed shiftsAmt = _summary[i].shiftsAmt;
	fixed countsAmt = _summary[i].countsAmt;
	fixed overShortAmt = countsAmt - shiftsAmt;

	// Add to table to show to user
	ListViewItem* item = new ListViewItem(tenderList, last);
	last = item;
	item->setValue(0, tender.name());
	item->setValue(1, shiftsAmt);
	item->setValue(2, countsAmt);
	item->setValue(3, overShortAmt);

	// Add to over/short if there is an amount
	if (overShortAmt != 0.0) {
	    TenderLine info;
	    info.tender_id = tender.id();
	    info.conv_amt = overShortAmt;
	    info.conv_rate = tender.convertRate();
	    info.amount = overShortAmt * tender.convertRate();
	    info.amount.moneyRound();
	    info.is_change = false;
	    info.voided = false;
	    adjustment.tenders().push_back(info);
	    overShort += info.amount;
	}

	// Add counted to transfer in/out
	TenderLine info;
	info.tender_id = tender.id();
	info.conv_amt = countsAmt;
	info.conv_rate = tender.convertRate();
	info.amount = countsAmt * tender.convertRate();
	info.amount.moneyRound();
	info.is_change = false;
	info.voided = false;
	transIn.tenders().push_back(info);

	transferAmt += info.amount;
	info.amount = -info.amount;
	info.conv_amt = -info.conv_amt;
	transOut.tenders().push_back(info);

	shiftsTotal += shiftsAmt;
	countsTotal += countsAmt;
    }

    // Add total line
    ListViewItem* item = new ListViewItem(tenderList, last);
    item->setValue(0, tr("Total"));
    item->setValue(1, shiftsTotal);
    item->setValue(2, countsTotal);
    item->setValue(3, countsTotal - shiftsTotal);

    // Show table to user and allow cancel or post
    QApplication::restoreOverrideCursor();
    int ch = dialog->exec();
    if (ch != QDialog::Accepted) return;

    // Check total over/short
    if (overShort > 5.0 || overShort < -5.0) {
	QString message = tr("Warning - your over/short is large.\n"
			     "Are you sure you mean to post this?");
	int ch = QMessageBox::warning(this, tr("Post?"), message,
				      QMessageBox::No, QMessageBox::Yes);
	if (ch != QMessageBox::Yes) return;
    }

    QApplication::setOverrideCursor(waitCursor);
    qApp->processEvents();

    // Add accounts to adjustment
    adjustment.accounts().push_back(AccountLine(adjust_id, -overShort));
    for (i = 0; i < adjustment.tenders().size(); ++i) {
	Id tender_id = adjustment.tenders()[i].tender_id;
	fixed amount = adjustment.tenders()[i].amount;

	Tender tender;
	findTender(tender_id, tender);

	Id tender_acct = tender.accountId();
	if (_company.shiftMethod() == Company::BY_STATION) {
	    if (adjustment.stationId() == safe_station_id)
		if (tender.safeId() != INVALID_ID)
		    tender_acct = tender.safeId();
	} else {
	    if (adjustment.employeeId() == safe_employee_id)
		if (tender.safeId() != INVALID_ID)
		    tender_acct = tender.safeId();
	}

	adjustment.accounts().push_back(AccountLine(tender_acct, amount));
    }

    // Add accounts to transfer out
    transOut.accounts().push_back(AccountLine(transfer_id, transferAmt));
    for (i = 0; i < transOut.tenders().size(); ++i) {
	Id tender_id = transOut.tenders()[i].tender_id;
	fixed amount = transOut.tenders()[i].amount;

	Tender tender;
	findTender(tender_id, tender);

	Id tender_acct = tender.accountId();
	if (_company.shiftMethod() == Company::BY_STATION) {
	    if (transOut.stationId() == safe_station_id)
		if (tender.safeId() != INVALID_ID)
		    tender_acct = tender.safeId();
	} else {
	    if (transOut.employeeId() == safe_employee_id)
		if (tender.safeId() != INVALID_ID)
		    tender_acct = tender.safeId();
	}

	transOut.accounts().push_back(AccountLine(tender_acct, amount));
    }

    // Add accounts to transfer in
    transIn.accounts().push_back(AccountLine(transfer_id, -transferAmt));
    for (i = 0; i < transIn.tenders().size(); ++i) {
	Id tender_id = transIn.tenders()[i].tender_id;
	fixed amount = transIn.tenders()[i].amount;

	Tender tender;
	findTender(tender_id, tender);

	Id tender_acct = tender.safeId();
	if (tender_acct == INVALID_ID)
	    tender_acct = tender.accountId();

	transIn.accounts().push_back(AccountLine(tender_acct, amount));
    }

    // Post adjustment if any tenders
    if (adjustment.tenders().size() > 0) {
	QApplication::restoreOverrideCursor();
	if (!_quasar->db()->create(adjustment)) {
	    QString message = tr("Failed creating over/short transaction");
	    QMessageBox::critical(this, tr("Error"), message);
	    return;
	}
    }

    // Post transfers
    if (!_quasar->db()->create(transOut)) {
	QApplication::restoreOverrideCursor();
	QString message = tr("Failed creating transfer out transaction");
	QMessageBox::critical(this, tr("Error"), message);
	if (adjustment.id() != INVALID_ID)
	    _quasar->db()->remove(adjustment);
	return;
    }
    if (!_quasar->db()->create(transIn)) {
	QApplication::restoreOverrideCursor();
	QString message = tr("Failed creating transfer in transaction");
	QMessageBox::critical(this, tr("Error"), message);
	if (adjustment.id() != INVALID_ID)
	    _quasar->db()->remove(adjustment);
	_quasar->db()->remove(transOut);
	return;
    }

    // Link the transfers
    _quasar->db()->linkTx(transOut.id(), transIn.id());

    // Set shift in shifts
    for (int cnt = shifts.size() - 1; cnt >= 0; --cnt) {
	Shift shift = shifts[cnt];
	shift.setShiftId(shift_id);
	shift.setAdjustmentId(adjustment.id());
	shift.setTransferId(transOut.id());
	_quasar->db()->update(shifts[cnt], shift);
    }

    // Set shift in counts
    for (i = 0; i < counts.size(); ++i) {
	TenderCount count = counts[i];
	count.setShiftId(shift_id);
	_quasar->db()->update(counts[i], count);
    }

    Company orig, company;
    _quasar->db()->lookup(orig);
    company = orig;

    company.setSafeStore(safe_store_id);
    company.setSafeStation(safe_station_id);
    company.setSafeEmployee(safe_employee_id);
    company.setOverShortAccount(adjust_id);
    company.setTransferAccount(transfer_id);
    _quasar->db()->update(orig, company);

    QApplication::restoreOverrideCursor();
    slotRefresh();
}
コード例 #22
0
ファイル: shaderfactory.cpp プロジェクト: Elavina6/drishti
bool
ShaderFactory::loadShader(GLhandleARB &progObj,
			  QString shaderString)
{
  GLhandleARB fragObj = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);  
  glAttachObjectARB(progObj, fragObj);

  GLhandleARB vertObj = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);  
  glAttachObjectARB(progObj, vertObj);

  {  // vertObj
    QString qstr;
    qstr = "varying vec3 pointpos;\n";
    qstr += "void main(void)\n";
    qstr += "{\n";
    qstr += "  // Transform vertex position into homogenous clip-space.\n";
    qstr += "  gl_FrontColor = gl_Color;\n";
    qstr += "  gl_BackColor = gl_Color;\n";
    qstr += "  gl_Position = ftransform();\n";
    qstr += "  gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n";
    qstr += "  gl_TexCoord[1] = gl_TextureMatrix[1] * gl_MultiTexCoord1;\n";
    qstr += "  gl_TexCoord[2] = gl_TextureMatrix[2] * gl_MultiTexCoord2;\n";
    qstr += "  gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;\n";
    qstr += "  pointpos = gl_Vertex.xyz;\n";
    qstr += "}\n";
    
    int len = qstr.length();
    char *tbuffer = new char[len+1];
    sprintf(tbuffer, qstr.toLatin1().data());
    const char *sstr = tbuffer;
    glShaderSourceARB(vertObj, 1, &sstr, NULL);
    delete [] tbuffer;

    GLint compiled = -1;
    glCompileShaderARB(vertObj);
    glGetObjectParameterivARB(vertObj,
			      GL_OBJECT_COMPILE_STATUS_ARB,
			      &compiled);
    if (!compiled)
      {
	GLcharARB str[1000];
	GLsizei len;
	glGetInfoLogARB(vertObj,
			(GLsizei) 1000,
			&len,
			str);
	
	QMessageBox::information(0,
				 "Error : Vertex Shader",
				 str);
	return false;
    }
  }
    
    
  { // fragObj
    int len = shaderString.length();
    char *tbuffer = new char[len+1];
    sprintf(tbuffer, shaderString.toLatin1().data());
    const char *sstr = tbuffer;
    glShaderSourceARB(fragObj, 1, &sstr, NULL);
    delete [] tbuffer;
  
    GLint compiled = -1;
    glCompileShaderARB(fragObj);
    glGetObjectParameterivARB(fragObj,
			    GL_OBJECT_COMPILE_STATUS_ARB,
			      &compiled);
    if (!compiled)
      {
	GLcharARB str[1000];
	GLsizei len;
	glGetInfoLogARB(fragObj,
			(GLsizei) 1000,
			&len,
			str);
	
	//-----------------------------------
	// display error
	
	//qApp->beep();
	
	QString estr;
	QStringList slist = shaderString.split("\n");
	for(int i=0; i<slist.count(); i++)
	  estr += QString("%1 : %2\n").arg(i+1).arg(slist[i]);
	
	QTextEdit *tedit = new QTextEdit();
	tedit->insertPlainText("-------------Error----------------\n\n");
	tedit->insertPlainText(str);
	tedit->insertPlainText("\n-----------Shader---------------\n\n");
	tedit->insertPlainText(estr);
	
	QVBoxLayout *layout = new QVBoxLayout();
	layout->addWidget(tedit);
	
	QDialog *showError = new QDialog();
	showError->setWindowTitle("Error in Fragment Shader");
	showError->setSizeGripEnabled(true);
	showError->setModal(true);
	showError->setLayout(layout);
	showError->exec();
	//-----------------------------------
	
	return false;
      }
  }

  
  //----------- link program shader ----------------------
  GLint linked = -1;
  glLinkProgramARB(progObj);
  glGetObjectParameterivARB(progObj, GL_OBJECT_LINK_STATUS_ARB, &linked);
  if (!linked)
    {
      GLcharARB str[1000];
      GLsizei len;
      QMessageBox::information(0,
			       "ProgObj",
			       "error linking texProgObj");
      glGetInfoLogARB(progObj,
		      (GLsizei) 1000,
		      &len,
		      str);
      QMessageBox::information(0,
			       "Error",
			       QString("%1\n%2").arg(len).arg(str));
      return false;
    }

  glDeleteObjectARB(fragObj);
  glDeleteObjectARB(vertObj);

  return true;
}
コード例 #23
0
ファイル: servicesection.cpp プロジェクト: balamyt92/AutoInfo
void ServiceSection::editSection()
{
    QModelIndexList index = ui->tableView->selectionModel()->selectedIndexes();
    if(index.isEmpty())
        return;
    if(sectionIsOpen)
    {

        QSqlQuery query("SELECT ID, Name FROM services "
                        "WHERE ID_Parent IS NULL "
                        "ORDER BY Name ASC ");
        QStringList id;
        QStringList name;
        while (query.next())
        {
            id << query.value(0).toString();
            name << query.value(1).toString();
        }

        QDialog *edit = new QDialog(this);
        edit->setWindowTitle("Редактирование услуги");
        QLabel *sectionName = new QLabel(tr("Раздел"), this);
        QLabel *nameLable = new QLabel(tr("Наименование"), edit);
        QLineEdit *line = new QLineEdit(edit);
        QComboBox *box = new QComboBox(edit);
        QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok |
                                                         QDialogButtonBox::Cancel, edit);
        connect(buttons, SIGNAL(accepted()), edit, SLOT(accept()));
        connect(buttons, SIGNAL(rejected()), edit, SLOT(reject()));

        QGridLayout *grid = new QGridLayout(edit);
        grid->addWidget(nameLable, 0, 0, 1, 1);
        grid->addWidget(sectionName, 1, 0, 1, 1);
        grid->addWidget(line, 0, 1, 1, 1);
        grid->addWidget(box, 1, 1, 1, 1);
        grid->addWidget(buttons, 2, 1, 1, 1);
        edit->setLayout(grid);

        line->setText(index.at(1).data().toString());
        box->addItems(name);
        int i = 0;
        for(; i < id.count(); ++i)
        {
            if(id.at(i).toInt() == index.at(3).data().toInt())
                break;
        }
        box->setCurrentIndex(i);

        if(edit->exec() == QDialog::Accepted)
        {
            query.prepare("UPDATE services SET ID_Parent="
                          + id.at(box->currentIndex()) +
                          ", Name=\'" + line->text() + "\'"
                          " WHERE ID=" + index.at(0).data().toString());
            query.exec();
            model->select();
            ui->tableView->setFocus();
        }

    }
    else
    {
        START:
        bool ok = false;
        QString newName = QInputDialog::getText(this, "Введите новое имя раздела",
                                                "Новое имя", QLineEdit::Normal,
                                                index.at(1).data().toString(), &ok);
        if(ok)
        {
            if(newName.isEmpty())
            {
                QMessageBox::critical(this, "Ошибка", "Имя не может быть пустым", QMessageBox::Ok);
                goto START;
            }

            if(!proxy->setData(index.at(1),newName))
            {
                QMessageBox::critical(this, "Ошибка", "Недопустимое имя", QMessageBox::Ok);
                goto START;
            }
            if(!model->submitAll())
            {
                QMessageBox::critical(this, "Ошибка", model->lastError().text(), QMessageBox::Ok);
                goto START;
            }
        }
    }
}
コード例 #24
0
ファイル: main.cpp プロジェクト: mgottschlag/kwin-tiling
int kScreenSaverMain( int argc, char** argv, KScreenSaverInterface& screenSaverInterface )
{
    KLocale::setMainCatalog("libkscreensaver");
    KCmdLineArgs::init(argc, argv, screenSaverInterface.aboutData());


    KCmdLineOptions options;

    options.add("setup", ki18n("Setup screen saver"));

    options.add("window-id wid", ki18n("Run in the specified XWindow"));

    options.add("root", ki18n("Run in the root XWindow"));

    options.add("demo", ki18n("Start screen saver in demo mode"), "default");

    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    // Set a useful default icon.
    app.setWindowIcon(KIcon("preferences-desktop-screensaver"));


    if (!pipe(termPipe))
    {
#ifndef Q_WS_WIN
        struct sigaction sa;
        sa.sa_handler = termHandler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        sigaction(SIGTERM, &sa, 0);
#endif
        QSocketNotifier *sn = new QSocketNotifier(termPipe[0], QSocketNotifier::Read, &app);
        QObject::connect(sn, SIGNAL(activated(int)), &app, SLOT(quit()));
    }

#ifdef Q_WS_X11
    oldXErrorHandler = XSetErrorHandler(xErrorHandler);
#endif
    KCrash::setCrashHandler( crashHandler );
    KGlobal::locale()->insertCatalog("klock");
    KGlobal::locale()->insertCatalog("kscreensaver");

    DemoWindow *demoWidget = 0;
    Window saveWin = 0;
    KScreenSaver *target;

    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    if (args->isSet("setup"))
    {
       QDialog *dlg = screenSaverInterface.setup();
       args->clear();
       dlg->exec();
       delete dlg;
       return 0;
    }

    if (args->isSet("window-id"))
    {
#ifdef Q_WS_WIN
        saveWin = (HWND)(args->getOption("window-id").toULong());
#else
        saveWin = args->getOption("window-id").toInt();
#endif
    }

#ifdef Q_WS_X11 //FIXME
    if (args->isSet("root"))
    {
		QX11Info inf;
        saveWin = RootWindow(QX11Info::display(), inf.screen());
    }
#endif

    if (args->isSet("demo"))
    {
        saveWin = 0;
    }

    if (saveWin == 0)
    {
        demoWidget = new DemoWindow();
        demoWidget->setAttribute(Qt::WA_NoSystemBackground);
        demoWidget->setAttribute(Qt::WA_PaintOnScreen);
        demoWidget->show();
        app.processEvents();
        saveWin = demoWidget->winId();
    }

    target = screenSaverInterface.create( saveWin );
    target->setAttribute(Qt::WA_PaintOnScreen);
    target->show();

    if (demoWidget)
    {
        target->installEventFilter( demoWidget );
    }

    args->clear();
    app.exec();

    delete target;
    delete demoWidget;

    return 0;
}
コード例 #25
0
ファイル: DossierEditeur.cpp プロジェクト: atchandj/LO21
void DossierEditeur::afficherProfil()
{
    try
    {
        QDialog* window = new QDialog(this);
        QGridLayout* lay = new QGridLayout;
        QPushButton* ok = new QPushButton("Ok");
        window->setWindowTitle("Profil");
        window->setFixedSize(400, 400);

        QStringList Formation = Dossier::getInstance().ListeCursus();
        int j = 1;
        QTableWidget* valide = new QTableWidget(1,1,this);
        QTableWidget* non_valide = new QTableWidget(1,1,this);
        QLabel* valideLabel = new QLabel("Validé :",this);
        QLabel* NonvalideLabel = new QLabel("A Valider :",this);
        valide->horizontalHeader()->hide();
        non_valide->horizontalHeader()->hide();
        valide->verticalHeader()->hide();
        non_valide->verticalHeader()->hide();
        valide->setMaximumSize(50,25);
        non_valide->setMaximumSize(50,25);

        QTableWidgetItem* ItemValide = new QTableWidgetItem("");
        ItemValide->setBackground(Qt::red);
        valide->setItem(0,0,ItemValide);

        QTableWidgetItem* ItemNonValide = new QTableWidgetItem("");
        ItemNonValide ->setBackground(Qt::gray);
        non_valide->setItem(0,0,ItemNonValide);
        //Tableaus affichant le nombre de crédits obtenu par catégorie
        for(QList<QString>::iterator it1 = Formation.begin(); it1 < Formation.end(); ++it1)
        {
            QMap<QString, unsigned int> ListeProfil = Dossier::getInstance().ListeProfil(*it1);
            QStringList P = ListeProfil.keys();
            QTableWidget* tab = new QTableWidget(1,ListeProfil.size(),this);
            tab->setHorizontalHeaderLabels(P);
            tab->setSelectionBehavior(QAbstractItemView::SelectRows);
            tab->verticalHeader()->hide();


            int i = 0;
            for(QList<QString>::iterator it2 = P.begin(); it2 < P.end(); ++it2)
            {
                QString cr; cr.setNum(ListeProfil[*it2]);
                QString creditFormation; creditFormation.setNum(FormationManager::getInstance().getFormation(*it1).getProfil(*it2));
                QString credit = cr +QString("(")+creditFormation+QString(")");
                QTableWidgetItem* monItem = new QTableWidgetItem(credit);
                if(FormationManager::getInstance().isFinished(*it1,*it2,ListeProfil[*it2]))
                    monItem->setBackground(Qt::red);
                else
                    monItem->setBackground(Qt::gray);
                tab->setItem(0,i,monItem);
                i++;
            }
            QLabel* form = new QLabel(*it1,this);
            lay->addWidget(form,j,0,1,3,Qt::AlignLeft);
            lay->addWidget(tab,j,1,1,3,Qt::AlignJustify);
            j++;
        }

        lay->addWidget(valideLabel,0,0);
        lay->addWidget(valide,0,1);
        lay->addWidget(NonvalideLabel,0,2);
        lay->addWidget(non_valide,0,3);
        lay->addWidget(ok,j,1,Qt::AlignHCenter);
        window->setLayout(lay);

        connect(ok,SIGNAL(clicked()),window,SLOT(accept()));
        window->exec();

        if(window->result())
        {

        }

    }
    catch(UTProfilerException& e)
    {
        QMessageBox::warning(this, "Ajout d'inscription", e.getInfo());
    }
}
コード例 #26
0
void MainWindow::on_btnLinkKey_clicked()
{
    WRITE2LOG("Linking...");
    if(certList.isEmpty() == true)
    {
        WRITE2LOG("Certificate list is empty");
        return;
    }

    if(ui->listCerts->currentIndex().row() == -1)
    {
        QMessageBox::warning(this, "Warning", "Select certificate!");
        return;
    }

    DWORD pcbData = 0;
    if(CertGetCertificateContextProperty(certList[ui->listCerts->currentIndex().row()], CERT_KEY_PROV_INFO_PROP_ID, NULL, &pcbData) != 0)
    {
        int result = QMessageBox::warning(this, "Warning", "This certificate already have private key.\nAre you sure you want to add new key?", QMessageBox::Ok, QMessageBox::Cancel);
        if (result == QMessageBox::Cancel)
        {
            WRITE2LOG("Canceled by user");
            return;
        }
    }

    QDialog* keyInfoDlg = new QDialog(this);
    QLineEdit* lnProvider = new QLineEdit;
    QLineEdit* lnLabel = new QLineEdit;


    QFormLayout* layout = new QFormLayout(keyInfoDlg);
    layout->addRow("CNG Cryptoprovider:", lnProvider);
    layout->addRow("Key name:", lnLabel);


    QDialogButtonBox *btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(btnBox, SIGNAL(accepted()), keyInfoDlg, SLOT(accept()));
    connect(btnBox, SIGNAL(rejected()), keyInfoDlg, SLOT(reject()));
    layout->addRow(btnBox);
    keyInfoDlg->exec();

    if(keyInfoDlg->result() == QDialog::Rejected)
    {
//        delete keyInfoDlg;
//        delete lnProvider;
//        delete lnLabel;
//        delete layout;
//        delete btnBox;
        WRITE2LOG("Canceled by user");
        return;
    }

    if(lnProvider->text().size() == 0 || lnLabel->text().size() == 0 )
    {
        QMessageBox::warning(this, "Warning", "All fields must be filled!", QMessageBox::Ok);
//        delete keyInfoDlg;
//        delete lnProvider;
//        delete lnLabel;
//        delete layout;
//        delete btnBox;
        return;
    }


    QString containerName = lnLabel->text();
    wchar_t* pwszContainerName = new wchar_t[containerName.size()];
    int size = containerName.toWCharArray(pwszContainerName);
    pwszContainerName[size] = 0;

    wchar_t* pwszProvider = new wchar_t[lnProvider->text().size()];
    size = lnProvider->text().toWCharArray(pwszProvider);
    pwszProvider[size] = 0;

    CRYPT_KEY_PROV_INFO kpi;
    ZeroMemory(&kpi, sizeof(kpi));

    kpi.pwszContainerName = pwszContainerName;
    kpi.dwProvType = NULL;
    kpi.pwszProvName = pwszProvider;

    LPCWSTR storage = L"";
    if(ui->rbMYStorage->isChecked() == true)
        storage = L"MY";
    else
        storage = L"ROOT";


    HCERTSTORE hCertStore = CertOpenStore(
           CERT_STORE_PROV_SYSTEM,
           0,
           NULL,
           CERT_SYSTEM_STORE_CURRENT_USER,
           storage);

    int res = CertSetCertificateContextProperty(certList[ui->listCerts->currentIndex().row()], CERT_KEY_PROV_INFO_PROP_ID, 0, &kpi);
    int ret = CertAddCertificateContextToStore(hCertStore, certList[ui->listCerts->currentIndex().row()], CERT_STORE_ADD_ALWAYS, NULL);
    if(res == 1 && ret == 1)
        QMessageBox::information(this, "Information", "Key was associated with certificate successfully. \nCertificate has been added to storage.", QMessageBox::Ok);
    else if (res == 0)
        QMessageBox::warning(this, "Warning", "Failed to associate key with certificate.", QMessageBox::Ok);
    else if (ret == 0)
        QMessageBox::warning(this, "Warning", "Failed to add certificate to store.", QMessageBox::Ok);

    delete keyInfoDlg;
    delete lnProvider;
    delete lnLabel;
    delete layout;
    delete btnBox;
    delete pwszContainerName;
    delete pwszProvider;
}
コード例 #27
0
void SWCRadiusPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent)
{
	if (menu_name == tr("neuron_radius"))
	{
		QDialog * dialog = new QDialog();
		QLineEdit * inimg_box = new QLineEdit("");
		QLineEdit * inswc_box = new QLineEdit("");
		QLineEdit * outswc_box = new QLineEdit("(optional)");
		QLineEdit * thresh_box = new QLineEdit("40");
		QCheckBox * is2d_checker = new QCheckBox("Is 2D radius");
		is2d_checker->setChecked(true);
		{
			QGridLayout * layout = new QGridLayout;
			layout->addWidget(new QLabel("Image path"), 0, 0, 1, 1);
			layout->addWidget(inimg_box, 0, 1, 1, 5);
			layout->addWidget(new QLabel("In swc path"), 1, 0, 1, 1);
			layout->addWidget(inswc_box, 1, 1, 1, 5);
			layout->addWidget(new QLabel("Threshold"), 2, 0, 1, 1);
			layout->addWidget(thresh_box, 2, 1, 1, 5);
			layout->addWidget(new QLabel("Out swc path"), 3, 0, 1, 1);
			layout->addWidget(outswc_box, 3, 1, 1, 5);
			layout->addWidget(is2d_checker, 4, 0, 1, 6);
			QPushButton * ok = new QPushButton("Ok");
			QPushButton * cancel = new QPushButton("Cancel");
			ok->setDefault(true);
			layout->addWidget(ok, 5, 0, 1, 3); 
			layout->addWidget(cancel, 5, 3, 1, 3); 
			dialog->setLayout(layout);
			connect(ok, SIGNAL(clicked()), dialog, SLOT(accept()));
			connect(cancel, SIGNAL(clicked()), dialog, SLOT(reject()));
		}
		if(dialog->exec() != QDialog::Accepted) return;

		string inimg_file = inimg_box->text().toStdString();
		string inswc_file = inswc_box->text().toStdString();
		string outswc_file =outswc_box->text().toStdString();
		if(outswc_file == "" || outswc_file == "(optional)") outswc_file = inswc_file + ".out.swc";
		bool is_2d = is2d_checker->isChecked(); 

		double bkg_thresh = atof(thresh_box->text().toStdString().c_str());
		cout<<"inimg_file = "<<inimg_file<<endl;
		cout<<"inswc_file = "<<inswc_file<<endl;
		cout<<"outswc_file = "<<outswc_file<<endl;
		cout<<"bkg_thresh = "<<bkg_thresh<<endl;
        
        if (dialog) {delete dialog; dialog=0;}
		
		unsigned char * inimg1d = 0; 
		V3DLONG * in_sz = 0;
		int datatype;
		if(!loadImage((char*)inimg_file.c_str(), inimg1d, in_sz, datatype))
		{
			QMessageBox::information(0,"","Invalid Image!");
			return;
		}
		vector<MyMarker*> inswc = readSWC_file(inswc_file);
		if(inswc.empty()) return;
		for(int i = 0; i < inswc.size(); i++)
		{
			MyMarker * marker = inswc[i];
			if(is_2d)
				marker->radius = markerRadiusXY(inimg1d, in_sz, *marker, bkg_thresh);
			else
				marker->radius = markerRadius(inimg1d, in_sz, *marker, bkg_thresh);
		}
		saveSWC_file(outswc_file, inswc);
		QMessageBox::information(0,"", string("neuron radius is calculated successfully. \n\nThe output swc is saved to " +outswc_file).c_str());
		for(int i = 0; i < inswc.size(); i++) delete inswc[i];
		if(inimg1d){delete [] inimg1d; inimg1d = 0;}
		if(in_sz){delete [] in_sz; in_sz = 0;}
	}
	else
	{
		v3d_msg(tr("Re-estimate the radius of a swc. "
			"Developed by Hang Xiao, 2012-11-07"));
	}
}
コード例 #28
0
void Documents::sOpenDoc(QString mode)
{
  QString ui;
  QString docType = _doc->currentItem()->rawValue("target_type").toString();
  int targetid = _doc->currentItem()->id("target_number");
  ParameterList params;
  params.append("mode", mode);

  //image -- In the future this needs to be changed to use docass instead of imageass
  if (docType == "IMG")
  {
    params.append("imageass_id", _doc->id());
    imageAssignment newdlg(this, "", TRUE);
    newdlg.set(params);

    if (newdlg.exec() != QDialog::Rejected)
    refresh();
    return;
  }
  //url -- In the future this needs to be changed to use docass instead of url
  else if (docType == "URL")
  {
   //If url scheme is missing, we'll assume it is "file" for now.
    QUrl url(_doc->currentItem()->rawValue("description").toString());
    if (url.scheme().isEmpty())
      url.setScheme("file");
    QDesktopServices::openUrl(url);
    return;
  }
  else if (docType == "INCDT")
  {
    params.append("incdt_id", targetid);
    ui = "incident";
  }
  else if (docType == "TODO")
  {
    params.append("todoitem_id", targetid);
    ui = "todoItem";
  }
  else if (docType == "OPP")
  {
    params.append("ophead_id", targetid);
    ui = "opportunity";
  }
  else if (docType == "J")
  {
    params.append("prj_id", targetid);
    ui = "project";
  }
  else if (docType == "CRMA")
  {
    params.append("crmacct_id", targetid);
    ui = "crmaccount";
  }
  else if (docType == "T")
  {
    params.append("cntct_id", targetid);
  }
  else if (docType == "V")
  {
    params.append("vend_id", targetid);
    ui = "vendor";
  }
  else if (docType == "I")
  {
    params.append("item_id", targetid);
    ui = "item";
  }
  else if (docType == "S")
  {
    params.append("sohead_id", targetid);
    ui = "salesOrder";
  }
  else if (docType == "P")
  {
    params.append("pohead_id", targetid);
    ui = "purchaseOrder";
  }
  else if (docType == "W")
  {
    params.append("wo_id", targetid);
    ui = "workOrder";
  }
  else if (docType == "EMP")
  {
    params.append("emp_id", targetid);
    ui = "employee";
  }
  else if (docType == "C")
  {
    params.append("cust_id", targetid);
    ui = "customer";
  }
  else
  {
    QMessageBox::critical(this, tr("Error"),
                          tr("Unknown File Type."));
    return;
  }

  QWidget* w = 0;
  if (parentWidget()->window())
  {
    if (parentWidget()->window()->isModal())
      w = _guiClientInterface->openWindow(ui, params, parentWidget()->window() , Qt::WindowModal, Qt::Dialog);
    else
      w = _guiClientInterface->openWindow(ui, params, parentWidget()->window() , Qt::NonModal, Qt::Window);
  }

  if (w->inherits("QDialog"))
  {
    QDialog* newdlg = qobject_cast<QDialog*>(w);
    newdlg->exec();
  }

  refresh();
}
コード例 #29
0
void TASARIM_BATCH_BASE::SLOT_TEXT_EKLE_BUTTON_CLICKED()
{
    m_design_widget->RESET_VARIABLE();

    QDialog     * dialog      = new QDialog;
    QGridLayout * box_layout  = new QGridLayout;
    QLabel      * label       = new QLabel;
    QLineEdit   * line_edit   = new QLineEdit;
    QComboBox   * combobox_grup = new QComboBox;
    QPushButton * push_button = new QPushButton("Yazı Ekle");

    line_edit->setMinimumWidth(350);

    combobox_grup->addItem(tr("Add the Form "));
    combobox_grup->addItem("Add the Line");

    dialog->setLayout     (box_layout);
    box_layout->addWidget (label,         0, 0);
    box_layout->addWidget (line_edit,     0, 1);
    box_layout->addWidget (push_button,   0, 2);
    box_layout->addWidget (combobox_grup, 1, 1);

    combobox_grup->setVisible(false);

    connect( push_button, SIGNAL(clicked()), dialog, SLOT(close()));

    dialog->exec();

    if ( line_edit->text().isEmpty() EQ true ) {
        return;
    }

//    int text_grup = combobox_grup->currentIndex();

    QLabel * user_label = m_design_widget->CREATE_NEW_LABEL(line_edit->text());

    TASARIM_DEGISKENI * degisken =  new TASARIM_DEGISKENI(true);

    degisken->SET_TASARIM_ID( m_tasarim_id );
    degisken->SET_TEXT( line_edit->text() );
    degisken->SET_TEXT_SIZE( line_edit->text().size() ); // txt uzunlugu kadar
    degisken->SET_GRUP( USER_TEXT);

//    if ( text_grup EQ 0 ) {
//        degisken->SET_GRUP( USER_TEXT);
//    }
//    else {
//        degisken->SET_GRUP(LINE);
//    }
    degisken->SET_BELGE_DEGISKEN_ID( -1 );
    degisken->SET_DEGISKEN_ID(-1);

    degisken->SET_FONT_SIZE( 11 );
    if ( m_printer_type EQ DOT_MATRIX_PRINTER ) {
        degisken->SET_FONT_SIZE( 10 );
    }

    degisken->SET_ALIGN( 10 );
    degisken->SET_VISIBLE( true );
    degisken->SET_POS_X( 0.00 );
    degisken->SET_POS_Y( 0.00 );
    degisken->SET_SIZE_X( 0 );
    degisken->SET_SIZE_Y( 0 );

    degisken->SET_LABEL( user_label );

    if ( m_printer_type EQ DOT_MATRIX_PRINTER ) {
        degisken->SET_FONT_FAMILY("Monospace");
    }

    QFont font = user_label->font();
    font.setFamily(degisken->GET_FONT_FAMILY());
    user_label->setFont(font);

    user_label->setObjectName( QString::number( degisken->GET_PRIMARY_ID())+ "\t"+QString::number( degisken->GET_GRUP() ) );

    m_all_variables.append( degisken );

    m_design_widget->ADD_NEW_VARIABLE( 0, 0, user_label );

}
コード例 #30
0
bool TaskDlgPipeParameters::accept()
{
    std::string name = vp->getObject()->getNameInDocument();

    
    //see what to do with external references
    //check the prerequisites for the selected objects
    //the user has to decide which option we should take if external references are used
    PartDesign::Pipe* pcPipe = static_cast<PartDesign::Pipe*>(getPipeView()->getObject());
    auto pcActiveBody = PartDesignGui::getBodyFor(pcPipe, false);
  //auto pcActivePart = PartDesignGui::getPartFor(pcActiveBody, false);
    std::vector<App::DocumentObject*> copies;

    bool ext = false;
    if(!pcActiveBody->hasFeature(pcPipe->Spine.getValue()) && !pcActiveBody->getOrigin()->hasObject(pcPipe->Spine.getValue()))
        ext = true;
    else if(!pcActiveBody->hasFeature(pcPipe->AuxillerySpine.getValue()) && !pcActiveBody->getOrigin()->hasObject(pcPipe->AuxillerySpine.getValue()))
            ext = true;
    else {
        for(App::DocumentObject* obj : pcPipe->Sections.getValues()) {
            if(!pcActiveBody->hasFeature(obj) && !pcActiveBody->getOrigin()->hasObject(obj))
                ext = true;
        }
    }
    
    if(ext) {
        QDialog* dia = new QDialog;
        Ui_Dialog dlg;
        dlg.setupUi(dia);
        dia->setModal(true);
        int result = dia->exec();
        if(result == QDialog::DialogCode::Rejected)
            return false;
        else if(!dlg.radioXRef->isChecked()) {

            if(!pcActiveBody->hasFeature(pcPipe->Spine.getValue()) && !pcActiveBody->getOrigin()->hasObject(pcPipe->Spine.getValue())) {
                pcPipe->Spine.setValue(PartDesignGui::TaskFeaturePick::makeCopy(pcPipe->Spine.getValue(), "", dlg.radioIndependent->isChecked()),
                                        pcPipe->Spine.getSubValues());
                copies.push_back(pcPipe->Spine.getValue());
            }
            else if(!pcActiveBody->hasFeature(pcPipe->AuxillerySpine.getValue()) && !pcActiveBody->getOrigin()->hasObject(pcPipe->AuxillerySpine.getValue())){
                pcPipe->AuxillerySpine.setValue(PartDesignGui::TaskFeaturePick::makeCopy(pcPipe->AuxillerySpine.getValue(), "", dlg.radioIndependent->isChecked()),
                                        pcPipe->AuxillerySpine.getSubValues());
                copies.push_back(pcPipe->AuxillerySpine.getValue());
            }
    
            std::vector<App::DocumentObject*> objs;
            int index = 0;
            for(App::DocumentObject* obj : pcPipe->Sections.getValues()) {

                if(!pcActiveBody->hasFeature(obj) && !pcActiveBody->getOrigin()->hasObject(obj)) {
                    objs.push_back(PartDesignGui::TaskFeaturePick::makeCopy(obj, "", dlg.radioIndependent->isChecked()));
                    copies.push_back(objs.back());
                }
                else
                    objs.push_back(obj);

                index++;
            }

            pcPipe->Sections.setValues(objs);
        }
    }
    
    try {
        Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()");
        if (!vp->getObject()->isValid())
            throw Base::Exception(vp->getObject()->getStatusString());
        Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()");
        Gui::Command::commitCommand();
        
        //we need to add the copied features to the body after the command action, as otherwise freecad crashs unexplainable
        for(auto obj : copies) {
            //Dead code: pcActiveBody was previously used without checking for null, so it won't be null here either.
            //if(pcActiveBody)
            pcActiveBody->addFeature(obj);
            //else if (pcActivePart)
            //    pcActivePart->addObject(obj);
        }
    }
    catch (const Base::Exception& e) {
        QMessageBox::warning(parameter, tr("Input error"), QString::fromUtf8(e.what()));
        return false;
    }

    return true;
}