コード例 #1
0
//
// Contributors page
//
ContributorsPage::ContributorsPage(Context *context) : context(context)
{
    QStringList contributors;
    contributors.append("Alejandro Martinez");
    contributors.append("Alex Harsanyi");
    contributors.append("Alexandre Prokoudine");
    contributors.append("Andre Heider");
    contributors.append("Andrew Bryson");
    contributors.append("Andy Froncioni");
    contributors.append("Antonius Riha");
    contributors.append("Arun Horne");
    contributors.append("Austin Roach");
    contributors.append("Ben Walding");
    contributors.append("Berend De Schouwer");
    contributors.append("Bruno Assis");
    contributors.append("Chris Cleeland");
    contributors.append("Christian Charette");
    contributors.append("Claus Assmann");
    contributors.append("Dag Gruneau");
    contributors.append("Damien Grauser");
    contributors.append("Daniel Besse");
    contributors.append("Darren Hague");
    contributors.append("Dave Waterworth");
    contributors.append("Dean Junk");
    contributors.append("Dmitry Monakhov");
    contributors.append("Eric Brandt");
    contributors.append("Eric Murray");
    contributors.append("Erik Boto");
    contributors.append("Frank Zschockelt");
    contributors.append("Gareth Coco");
    contributors.append("Greg Lonnon");
    contributors.append("Henrik Johansson");
    contributors.append("Ilja Booij");
    contributors.append("Irvin Sirotić");
    contributors.append("Ivor Hewitt");
    contributors.append("Jaime Jofre");
    contributors.append("Jamie Kimberley");
    contributors.append("Jan de Visser");
    contributors.append("Jim Ley");
    contributors.append("Jörn Rischmüller");
    contributors.append("Johan Martensson");
    contributors.append("John Ehrlinger");
    contributors.append("Jon Beverley");
    contributors.append("Jon Escombe");
    contributors.append("Josef Gebel");
    contributors.append("Julian Baumgartner");
    contributors.append("Julian Simioni");
    contributors.append("Justin Knotzke");
    contributors.append("Keisuke Yamaguchi");
    contributors.append("Keith Reynolds");
    contributors.append("Ken Sallot");
    contributors.append("Leif Warland");
    contributors.append("Lucas Garoto");
    contributors.append("Luke NRG");
    contributors.append("Magnus Gille");
    contributors.append("Marc Boudreau");
    contributors.append("Marcel Breij");
    contributors.append("Mark Buller");
    contributors.append("Mark Liversedge");
    contributors.append("Mark Rages");
    contributors.append("Michael Puchowicz");
    contributors.append("Mitsukuni Sato");
    contributors.append("Ned Harding");
    contributors.append("Nicholas Feng");
    contributors.append("Nick Burrett");
    contributors.append("Okano Takayoshi");
    contributors.append("Omar Torres");
    contributors.append("Patrick McNerthney");
    contributors.append("Dr Phil Skiba");
    contributors.append("Philip Willoughby");
    contributors.append("Rainer Clasen");
    contributors.append("Ralf Spenneberg");
    contributors.append("Robb Romans");
    contributors.append("Robert Carlsen");
    contributors.append("Roberto Massa");
    contributors.append("Ron Alford");
    contributors.append("Satoru Kurashiki");
    contributors.append("Sean Rhea");
    contributors.append("Simon Brewer");
    contributors.append("Stefan Schake");
    contributors.append("Stephan Lips");
    contributors.append("Steven Gribble");
    contributors.append("Thomas Weichmann");
    contributors.append("Tilman Schmiedeberg");
    contributors.append("Ugo Borello");
    contributors.append("Vianney Boyer");
    contributors.append("Walter Bürki");
    contributors.append("Yves Arrouye");

    QString contributorsTable = "<center><table><tr>";
    for (int i=0;i<contributors.count();i++){
        contributorsTable.append("<td><center>"+contributors.at(i)+"</center></td>");
        if ((i+1) % 4 == 0)
            contributorsTable.append("</tr><tr>");
    }
    contributorsTable.append("</tr></table></center>");

    QLabel *text;
    text=new QLabel(this);
    text->setContentsMargins(0,0,0,0);
    text->setText(contributorsTable);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0,0,0,0);
    mainLayout->addWidget(text);

    setLayout(mainLayout);
}
コード例 #2
0
void AliasesFindDialog::Find(){
  
  QString StringFind;
  QString StringDomain;
  
  if( lineEdit_Domain->isEnabled() ){
	
	StringDomain.append("%");
	StringDomain.append(lineEdit_Domain->text());
	StringDomain.append("%");
  
  }else{
	
	StringDomain="%%";
  
  }

  StringFind.append("%");
  StringFind.append(lineEdit_Find->text());
  StringFind.append("%");

  TestQuery();
  
  if( db_psql.isOpen() ){ 	

	if(tableWidget_Find->isSortingEnabled()){
	  
	  tableWidget_Find->setSortingEnabled(false);

	}
	
	tableWidget_Find->clearContents();
	tableWidget_Find->setRowCount(0);
	
	QSqlQuery query( db_psql );
	
	if(comboBox->currentIndex() == 0){
	  
	  query.prepare("SELECT local_part,domain,recipients FROM aliases_view WHERE local_part ILIKE :find and domain ILIKE :domain");
	
	}else{
	  
	  query.prepare("SELECT local_part,domain,recipients FROM aliases_view WHERE recipients ILIKE :find and domain ILIKE :domain");
	
	}
	
	query.bindValue(":find", StringFind);
	query.bindValue(":domain", StringDomain);
	
	if( !query.exec() ){
	  
	  QMessageBox::warning(this, tr("Query Error"),
						   query.lastError().text(),
						   QMessageBox::Ok);
	  query.clear();
	  
	}else{
	  
	  for(int i = 0; i < query.size(); i++){
		
		query.next();
		tableWidget_Find->setRowCount(i + 1);
		
		__item0 = new QTableWidgetItem();
		__item0->setText(query.value(0).toString());
		tableWidget_Find->setItem(i, 0, __item0);
		
		__item1 = new QTableWidgetItem();
		__item1->setText(query.value(1).toString());
		tableWidget_Find->setItem(i, 1, __item1);
		
		__item2 = new QTableWidgetItem();
		__item2->setText(query.value(2).toString());
		tableWidget_Find->setItem(i, 2, __item2);
		
	  }
	  
	}
	
	tableWidget_Find->setSortingEnabled(true);

	query.clear();
	
  }else{
	
	this->reject();
	
  }
  
}
コード例 #3
0
bool QgsVectorLayerEditBuffer::commitChanges( QStringList& commitErrors )
{
  QgsVectorDataProvider* provider = L->dataProvider();
  commitErrors.clear();

  int cap = provider->capabilities();
  bool success = true;

  // geometry updates   attribute updates
  // yes                no                    => changeGeometryValues
  // no                 yes                   => changeAttributeValues
  // yes                yes                   => changeFeatures

  //
  // update geometries
  //
  if ( !mChangedGeometries.isEmpty() && (( cap & QgsVectorDataProvider::ChangeFeatures ) == 0 || mChangedAttributeValues.isEmpty() ) )
  {
    if ( provider->changeGeometryValues( mChangedGeometries ) )
    {
      commitErrors << tr( "SUCCESS: %n geometries were changed.", "changed geometries count", mChangedGeometries.size() );

      emit committedGeometriesChanges( L->id(), mChangedGeometries );
      mChangedGeometries.clear();
    }
    else
    {
      commitErrors << tr( "ERROR: %n geometries not changed.", "not changed geometries count", mChangedGeometries.size() );
      success = false;
    }
  }

  QgsFields oldFields = L->fields();

  //
  // delete attributes
  //
  bool attributesChanged = false;
  if ( !mDeletedAttributeIds.isEmpty() )
  {
    if (( cap & QgsVectorDataProvider::DeleteAttributes ) && provider->deleteAttributes( mDeletedAttributeIds.toSet() ) )
    {
      commitErrors << tr( "SUCCESS: %n attribute(s) deleted.", "deleted attributes count", mDeletedAttributeIds.size() );

      emit committedAttributesDeleted( L->id(), mDeletedAttributeIds );

      mDeletedAttributeIds.clear();
      attributesChanged = true;
    }
    else
    {
      commitErrors << tr( "ERROR: %n attribute(s) not deleted.", "not deleted attributes count", mDeletedAttributeIds.size() );
#if 0
      QString list = "ERROR: Pending attribute deletes:";
      Q_FOREACH ( int idx, mDeletedAttributeIds )
      {
        list.append( ' ' + L->pendingFields().at( idx ).name() );
      }
      commitErrors << list;
#endif
      success = false;
    }
  }
コード例 #4
0
ファイル: myprint.cpp プロジェクト: kanbodows/kafpocs
QTextDocument *MyPrint::print(QSqlQueryModel *model, RowList colHeaders, QString title, QString footer, int groupCols = 0)
{
    QString body;
    QStringList colls;
    body.append("<html><head>"
                "<link rel='stylesheet' type='text/css' href='format.css'>"
                "</head><body>");
    if (title!="")
        body.append("<center><H2>" + title + "</H2></center><br>");
    body.append("<center><table border='1' class = 'mine'><tr>");
    RowList::const_iterator i = colHeaders.constBegin();
    while (i != colHeaders.constEnd()) {
        colls.append(QString::number(i.key()));
        body.append("<th>" + i.value() + "</th>\n");
        ++i;
    }
    body.append("</tr>\n");
    while (model->canFetchMore())
        model->fetchMore();
    QMap<int,QString> groupTitles; // заголовки групп groupTitles(номер колонки, название группы)
    QMap<int,int> groupCounts; // количество элементов в группе groupCounts(номер колонки, кол-во)
    for (int index = 0; index < model->rowCount(); index++)
    {
        body.append("<tr>\n");
        for (int listId = 0; listId < colls.count(); listId++)
        {
            if(listId < groupCols) // если колонки нужно сгруппировать(если это групируемая колонка)
            {
                if(groupTitles.value(listId) != model->record(index).value(colls[listId].toInt()).toString())
                {
                    groupTitles[listId] = model->record(index).value(colls[listId].toInt()).toString();
                    body.append("<td class='grHead' colspan = '"+QString::number(colls.count()-listId)+"'><b>");
                    body.append(groupTitles[listId]);
                    body.append("</b></td>\n</tr>\n<tr>\n");
                    if(listId == groupCols-1)
                        for(int i=0; i < listId + 1; i++)
                            body.append("<td>1</td>\n");
                    else
                        for(int i=0; i < listId + 1; i++)
                            body.append("<td></td>\n");
                    groupCounts[listId] = 1;
                }
                else
                {
                    groupCounts[listId] = groupCounts[listId] + 1;
                    body.append("<td>" + QString::number(groupCounts[listId]) + "</td>\n");
                }
            }
            else
            {
                body.append("<td>");
                body.append(model->record(index).value(colls[listId].toInt()).toString());
                body.append("</td>\n");
            }
        }
        body.append("</tr>\n");
    }
    body.append("</table></center>");
    if (footer!="")

        body.append("<center>" + footer + "</center>");

    body.append("</body></html>");
//    qDebug()<<body;
    QTextDocument *toPrint = new QTextDocument;
    //    toPrint->addResource(QTextDocument::ImageResource, QUrl( "bg.png" ), QPixmap(":/img/img/institution_icon.png") );
    toPrint->addResource(QTextDocument::StyleSheetResource, QUrl( "format.css" ), css->reportCss);
    toPrint->setHtml(body);
    return toPrint;
}
コード例 #5
0
ファイル: findwidget.cpp プロジェクト: venkatarajasekhar/Qt
QT_BEGIN_NAMESPACE

FindWidget::FindWidget(QWidget *parent)
    : QWidget(parent)
    , appPalette(qApp->palette())
{
    TRACE_OBJ
    installEventFilter(this);
    QHBoxLayout *hboxLayout = new QHBoxLayout(this);
    QString resourcePath = QLatin1String(":/qt-project.org/assistant/images/");

#ifndef Q_OS_MAC
    hboxLayout->setMargin(0);
    hboxLayout->setSpacing(6);
    resourcePath.append(QLatin1String("win"));
#else
    resourcePath.append(QLatin1String("mac"));
#endif

    toolClose = setupToolButton(QLatin1String(""),
        resourcePath + QLatin1String("/closetab.png"));
    hboxLayout->addWidget(toolClose);
    connect(toolClose, SIGNAL(clicked()), SLOT(hide()));

    editFind = new QLineEdit(this);
    hboxLayout->addWidget(editFind);
    editFind->setMinimumSize(QSize(150, 0));
    connect(editFind, SIGNAL(textChanged(QString)), this,
        SLOT(textChanged(QString)));
    connect(editFind, SIGNAL(returnPressed()), this, SIGNAL(findNext()));
    connect(editFind, SIGNAL(textChanged(QString)), this, SLOT(updateButtons()));

    toolPrevious = setupToolButton(tr("Previous"),
        resourcePath + QLatin1String("/previous.png"));
    connect(toolPrevious, SIGNAL(clicked()), this, SIGNAL(findPrevious()));

    hboxLayout->addWidget(toolPrevious);

    toolNext = setupToolButton(tr("Next"),
        resourcePath + QLatin1String("/next.png"));
    hboxLayout->addWidget(toolNext);
    connect(toolNext, SIGNAL(clicked()), this, SIGNAL(findNext()));

    checkCase = new QCheckBox(tr("Case Sensitive"), this);
    hboxLayout->addWidget(checkCase);

    labelWrapped = new QLabel(this);
    labelWrapped->setScaledContents(true);
    labelWrapped->setTextFormat(Qt::RichText);
    labelWrapped->setMinimumSize(QSize(0, 20));
    labelWrapped->setMaximumSize(QSize(105, 20));
    labelWrapped->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignVCenter);
    labelWrapped->setText(tr("<img src=\":/qt-project.org/assistant/images/wrap.png\""
        ">&nbsp;Search wrapped"));
    hboxLayout->addWidget(labelWrapped);

    QSpacerItem *spacerItem = new QSpacerItem(20, 20, QSizePolicy::Expanding,
        QSizePolicy::Minimum);
    hboxLayout->addItem(spacerItem);
    setMinimumWidth(minimumSizeHint().width());
    labelWrapped->hide();

    updateButtons();
}
コード例 #6
0
ファイル: serialthread.cpp プロジェクト: DeuceEFI/emstudio
int SerialThread::readSerial(int timeout)
{
	if (!m_logInFile || !m_logInOutFile)
	{
		if (m_logsEnabled)
		{
			openLogs();
		}

	}
	qint64 currms = QDateTime::currentMSecsSinceEpoch();
	int readlen = m_buffer.size();
	QByteArray qbuffer;
	if (m_buffer.size() > 10240)
	{
		//Error here somehow;
		Q_ASSERT(m_buffer.size() < 10240);
	}
	unsigned char buffer[10240];
	qbuffer.append(m_buffer);
	/*for (int i=0;i<m_buffer.size();i++)
	{
		buffer[i] = m_buffer[i];
		qbuffer.append(m_buffer[i]);
	}*/
	m_buffer.clear();
	//bool inpacket = false;
	//bool inescape = false;
	QString byteoutofpacket;
	while (currms + timeout > QDateTime::currentMSecsSinceEpoch())
	{
#ifdef Q_OS_WIN32
		if (!ReadFile(m_portHandle,(LPVOID)buffer,1024,(LPDWORD)&readlen,NULL))
		{
			//Serial error here
			qDebug() << "Serial Read error";
		}
#else
		readlen = read(m_portHandle,buffer,1024);
#endif //Q_OS_WIN32
		if (readlen < 0)
		{
			//Nothing on the port
			msleep(10);
		}
		else
		{
			if (m_logsEnabled)
			{
				m_logInFile->write((const char*)buffer,readlen);
				m_logInFile->flush();
			}
		}
		if (readlen == 0)
		{
			msleep(10);
		}
		for (int i=0;i<readlen;i++)
		{
			if (buffer[i] == 0xAA)
			{
				if (m_inpacket)
				{
					//Start byte in the middle of a packet
					//Clear out the buffer and start fresh
					m_inescape = false;
					if (m_logsEnabled)
					{
						m_logWriteMutex.lock();
						m_logInOutFile->write(QByteArray().append(0xAA));
						QByteArray nbuffer(qbuffer);
						nbuffer.replace(0xBB,QByteArray().append(0xBB).append(0x44));
						nbuffer.replace(0xAA,QByteArray().append(0xBB).append(0x55));
						nbuffer.replace(0xCC,QByteArray().append(0xBB).append(0x33));
						m_logInOutFile->write((const char*)nbuffer.data(),nbuffer.size());
						m_logInOutFile->write(QByteArray().append(0xCC));
						m_logInOutFile->flush();
						m_logWriteMutex.unlock();
					}
					qbuffer.clear();
					qDebug() << "Buffer error";
					m_packetErrorCount++;
				}
				//qbuffer.append(buffer[i]);
				//qDebug() << "Start of packet";
				//Start of packet
				m_inpacket = true;
			}
			else if (buffer[i] == 0xCC && m_inpacket)
			{
				//qDebug() << "End of packet. Size:" << qbuffer.size();
				//End of packet
				m_inpacket = false;
				//qbuffer.append(buffer[i]);

				//m_logFile->flush();
				//emit parseBuffer(qbuffer);


				//New Location of checksum
				unsigned char sum = 0;
				for (int i=0;i<qbuffer.size()-1;i++)
				{
					sum += qbuffer[i];
				}
				if (m_logsEnabled)
				{
					m_logWriteMutex.lock();
					m_logInOutFile->write(QByteArray().append(0xAA));
					QByteArray nbuffer(qbuffer);
					nbuffer.replace(0xBB,QByteArray().append(0xBB).append(0x44));
					nbuffer.replace(0xAA,QByteArray().append(0xBB).append(0x55));
					nbuffer.replace(0xCC,QByteArray().append(0xBB).append(0x33));
					m_logInOutFile->write((const char*)nbuffer.data(),nbuffer.size());
					m_logInOutFile->write(QByteArray().append(0xCC));
					m_logInOutFile->flush();
					m_logWriteMutex.unlock();
				}
				//qDebug() << "Payload sum:" << QString::number(sum);
				//qDebug() << "Checksum sum:" << QString::number((unsigned char)currPacket[currPacket.length()-1]);
				if (sum != (unsigned char)qbuffer[qbuffer.size()-1])
				{
					qDebug() << "BAD CHECKSUM!";
					m_packetErrorCount++;
					//return QPair<QByteArray,QByteArray>();
				}
				else
				{
					m_packetErrorCount=0;
					m_queuedMessages.append(qbuffer.mid(0,qbuffer.length()-1));
				}
				//return qbuffer;
				QString output;
				for (int i=0;i<qbuffer.size();i++)
				{
					int num = (unsigned char)qbuffer[i];
					output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
				}
				//qDebug() << "Full packet:";
				//qDebug() << output;
				qbuffer.clear();
			}
			else
			{
				if (m_inpacket && !m_inescape)
				{
					if (buffer[i] == 0xBB)
					{
						//Need to escape the next byte
						//retval = logfile.read(1);
						m_inescape = true;
					}
					else
					{
						qbuffer.append(buffer[i]);
					}

				}
				else if (m_inpacket && m_inescape)
				{
					if (buffer[i] == 0x55)
					{
						qbuffer.append((char)0xAA);
					}
					else if (buffer[i] == 0x44)
					{
						qbuffer.append((char)0xBB);
					}
					else if (buffer[i] == 0x33)
					{
						qbuffer.append((char)0xCC);
					}
					else
					{
						qDebug() << "Error, escaped character is not valid!:" << QString::number(buffer[i],16);
						m_packetErrorCount++;
					}
					m_inescape = false;
				}
				else
				{
					//qDebug() << "Byte out of a packet:" << QString::number(buffer[i],16);
					byteoutofpacket += QString::number(buffer[i],16) + " ";
				}
			}
		}
		//qDebug() << "Bytes out of a packet:" << byteoutofpacket;
	}
	m_buffer.append(qbuffer);
	if (readlen > 0)
	{
	//m_buffer.write(buffer,readlen);
	//	m_buffer.append((const char*)buffer,readlen);
	}
	return m_packetErrorCount;
}
コード例 #7
0
ファイル: tictactoe.cpp プロジェクト: trixtur/QtTicTacToe
void TicTacToe::RunButtonPress(QPushButton *b)
{
    int quad = -1;
    if(b == ui->TopLeft_Button)
        quad = 0;
    if(b == ui->TopMiddle_Button)
        quad = 1;
    if(b == ui->TopRight_Button)
        quad = 2;
    if(b == ui->MiddleLeft_Button)
        quad = 3;
    if(b == ui->MiddleMiddle_Button)
        quad = 4;
    if(b == ui->MiddleRight_Button)
        quad = 5;
    if(b == ui->BottomLeft_Button)
        quad = 6;
    if(b == ui->BottomMiddle_Button)
        quad = 7;
    if(b == ui->BottomRight_Button)
        quad = 8;

    if(is_X)
    {
        is_X = false;
        SetButton(&b,"X");
    }
    else
    {
        is_X = true;
       SetButton(&b,"O");
    }

    if(quad == 0)
        ui->TopLeft_Button = b;
    if(quad == 1)
        ui->TopMiddle_Button = b;
    if(quad == 2)
        ui->TopRight_Button = b;
    if(quad == 3)
        ui->MiddleLeft_Button = b;
    if(quad == 4)
        ui->MiddleMiddle_Button = b;
    if(quad == 5)
        ui->MiddleRight_Button = b;
    if(quad == 6)
        ui->BottomLeft_Button = b;
    if(quad == 7)
        ui->BottomMiddle_Button = b;
    if(quad == 8)
        ui->BottomRight_Button = b;

    if(hasWinner())
    {
        QMessageBox::Icon w = QMessageBox::Information;
        QString s;
        s.append(&winner);
        s.append(" has won!");
        QMessageBox *winner = new QMessageBox("Winner",s,w,0,DIALOG_OK_BUTTON,0,this,Qt::MSWindowsFixedSizeDialogHint);
        winner->show();
        connect(winner,SIGNAL(finished(int)),this,SLOT(MBoxClose(int)));
        return;
    }

    if(isFull())
    {
        QMessageBox::Icon i = QMessageBox::Information;
        QMessageBox *b = new QMessageBox("CAT","The Game ended in a tie.",i,0,DIALOG_OK_BUTTON,0,this,Qt::MSWindowsFixedSizeDialogHint);
        b->show();
        connect(b,SIGNAL(finished(int)),this,SLOT(MBoxClose(int)));
    }
}
コード例 #8
0
ファイル: releasedialog.cpp プロジェクト: JinduYin/YQCMM
void ReleaseDialog::release()
{
    setTitle("发布版本");
    QString pwd = lineedit_pwd->text();
    QString name = lineedit_name->text();
    if(pwd.isEmpty() || name.isEmpty() || name.size() > 16)
    {
        QString prompt;
        prompt = QString("必须设置加密密码\n填写版本信息。");
        if(name.size() > 16)
            prompt = QString("版本信息不能超过16个字符。");
        QMessageBox box(QMessageBox::Information, "提示", prompt);
        box.setStandardButtons(QMessageBox::Ok);
        box.setButtonText(QMessageBox::Ok, "确定");
        box.exec();
        return;
    }

    ////name 最大16个字符
    if(!setFilePath())
    {
        QMessageBox::information(NULL, "提示", "文件路径设置失败!");
        return;
    }

    bar->setHidden(false);

    QDateTime start,end;
    getDateTime(start, end);
    QString jsonfilePath = getReadFilePath(start, end);

    this->setCursor(Qt::WaitCursor);
    ///读JSON下载资源
    readJsonFile(jsonfilePath);

    ///打包
    QStringList fileNames = getCurrentDirFiles(releasePath);
    QString destPath  = QCoreApplication::applicationDirPath();
    destPath.append("/ZIP/");
    QDir dir(destPath);
    if(!dir.exists())
        dir.mkpath(destPath);
    QString destName = currentDate.toString("yyyy-MM-dd_hh_mm_ss");
    destName.append(".zip");
    destPath.append(destName);

    QFile destFile(destPath);
    if(destFile.exists())
    {
    }

    zipFile zf;
    QByteArray dest = destPath.toLocal8Bit();
    zf = zipOpen(dest.data(), APPEND_STATUS_CREATE);


    if (zf == NULL)
    {
        QMessageBox::information(NULL, "提示", "打开压缩文件失败!");
        return;
    }

   label_title->setText("压缩文件……");
//   LOKI_ON_BLOCK_EXIT(zipClose, zf, (const char *)NULL);
   for (int i=0; i<fileNames.size(); i++)
   {
       QString tempStr = fileNames.at(i);
       QString path = releasePath;
       path.remove("music");
       QString temprel = path;
       QString deststr = tempStr.remove(temprel);
       if (!ZipAddFile(zf, deststr, fileNames.at(i),  pwd,  true)) //"default_yqc"
       {
           continue;
       }
   }

   int errclose = zipClose(zf, NULL);
   if (errclose != ZIP_OK)
       qDebug() << " zipClose ret : " << errclose;


   label_title->setText("上传压缩包……");

   QFile file(destPath);
   qDebug() << " size " << file.size();
   if(file.size()/1024/1024 >= 1024)
   {
        QMessageBox::information(this, "提示", "上传文件大小必须小于1G!");
        return;
   }
   ///上传打包文件
//   QString url;
//   CurlUpload *curlUpload = new CurlUpload();
//   bool ok = curlUpload->uploadYQDyun(destName, destPath, url);


//   if(!ok)
//   {
//       url = "";
//       label_title->setText("上传失败");
//       label_title->setStyleSheet("color:rgb(255, 0, 0);");
//   }
//   else
//   {
//       label_title->setText("上传成功");
//       label_title->setStyleSheet("color:rgb(0, 255, 0);");
//   }

//   qDebug() << " upload yun : ok : " << ok;
//   qDebug() << " zip name " << destName;
//   qDebug() << " url " << url;
//   /// post 表格数据
   QDateTime time = QDateTime::currentDateTime();
   QString timeStr = time.toString("yyyy-MM-dd-hh-mm-ss");
   int version = time.toTime_t(); ///时间戳
//   QString postStr = QString("name=%1&url=%2&time=%3&remark=%4&version=%5")
//                            .arg(name)
//                            .arg(url)
//                            .arg(timeStr)
//                            .arg(pwd)
//                            .arg(version);


//   CurlUpload *curlDownlaod = new CurlUpload();
//   curlDownlaod->postJson(postStr);


   _yun.name = name;
   _yun.timeStr = timeStr;
   _yun.pwd = pwd;
   _yun.version = QString::number(version);

   this->setCursor(Qt::ArrowCursor);
//   return;

   ////
   ///线程上传
   retSize = "-2";
   Thread *workerThread = new Thread(this, 4);
   connect(workerThread, &Thread::resultYun, this, &ReleaseDialog::uploadsuccess);
   connect(workerThread, &Thread::start_upload, this, &ReleaseDialog::timeStart);
   connect(workerThread, &Thread::finished, workerThread, &QObject::deleteLater);
   workerThread->setUploadYun(destName, destPath, &retSize);
   workerThread->start();
   startValue = true;
}
コード例 #9
0
ファイル: logloader.cpp プロジェクト: djandruczyk/emstune
void LogLoader::parseBuffer(QByteArray buffer)
{
	if (buffer.size() <= 3)
	{
		qDebug() << "Not long enough to even contain a header!";
		return;
	}

	//Trim off 0xAA and 0xCC from the start and end
	buffer = buffer.mid(1);
	buffer = buffer.mid(0,buffer.length()-1);

	//qDebug() << "Packet:" << QString::number(buffer[1],16) << QString::number(buffer[buffer.length()-2],16);
	QByteArray header;
	//currPacket.clear();
	//Parse the packet here
	int headersize = 3;
	int iloc = 0;
	bool seq = false;
	bool len = false;
	if (buffer[iloc] & 0x4)
	{
		//Has header
		seq = true;
		//qDebug() << "Has seq";
		headersize += 1;
	}
	if (buffer[iloc] & 0x1)
	{
		//Has length
		len = true;
		//qDebug() << "Has length";
		headersize += 2;
	}
	header = buffer.mid(0,headersize);
	iloc++;
	unsigned int payloadid = (unsigned int)buffer[iloc] << 8;

	payloadid += (unsigned char)buffer[iloc+1];
	//qDebug() << QString::number(payloadid,16);
	//qDebug() << QString::number(buffer[iloc-1],16);
	//qDebug() << QString::number(buffer[iloc],16);
	//qDebug() << QString::number(buffer[iloc+1],16);
	//qDebug() << QString::number(buffer[iloc+2],16);
	iloc += 2;
	//qDebug() << QString::number(payloadid,16);
	if (seq)
	{
		//qDebug() << "Sequence number" << QString::number(currPacket[iloc]);
		iloc += 1;
	}
	QByteArray payload;
	if (len)
	{
		//qDebug() << "Length found, buffer size:" << buffer.length() << "iloc:" << QString::number(iloc);
		unsigned int length = buffer[iloc] << 8;
		length += buffer[iloc+1];
		//qDebug() << "Length:" << length;
		iloc += 2;
		//curr += length;
		payload.append(buffer.mid(iloc,length));
	}
	else
	{
		//qDebug() << "Buffer length:" << buffer.length();
		//qDebug() << "Attempted cut:" << buffer.length() - iloc;
		payload.append(buffer.mid(iloc),(buffer.length()-iloc) -1);
	}
	//qDebug() << "Payload";
	QString output;
	for (int i=0;i<payload.size();i++)
	{
		int num = (unsigned char)payload[i];
		output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
	}
	//qDebug() << output;
	output.clear();
	//qDebug() << "Header";
	for (int i=0;i<header.size();i++)
	{
		int num = (unsigned char)header[i];
		output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
	}
	//qDebug() << output;
	//Last byte of currPacket should be out checksum.
	unsigned char sum = 0;
	for (int i=0;i<header.size();i++)
	{
		sum += header[i];
	}
	for (int i=0;i<payload.size();i++)
	{
		sum += payload[i];
	}
	//qDebug() << "Payload sum:" << QString::number(sum);
	//qDebug() << "Checksum sum:" << QString::number((unsigned char)currPacket[currPacket.length()-1]);
	if (sum != (unsigned char)buffer[buffer.length()-1])
	{
		qDebug() << "BAD CHECKSUM!";
		qDebug() << "header size:" << header.size();
		qDebug() << "payload size:" << payload.size();
	}
	else
	{
		//qDebug() << "Got full packet. Header length:" << header.length() << "Payload length:" << payload.length();
		emit payloadReceived(header,payload);
		//payload is our actual data.
		//unsigned int rpm = (payload[26] << 8) + payload[27];

		//qDebug() << "f" << f.getValue(&payload);
		//qDebug() << QString::number(rpm);
		//qDebug() << QString::number(((unsigned short)payload[8] << 8) + (unsigned short)payload[9]);
	}
}
コード例 #10
0
ファイル: parser.cpp プロジェクト: DenisChernov/irbis64
QString parser::parseUserData(QString rawData)
{
    cout << "parsing user raw data" << endl;
    
    vector <QString> clearedData;
    QString finalData;
    int amountFields = sizeof(fieldID) / sizeof(*fieldID);
    
    QStringList strList;
    strList = rawData.split("\n", QString::SkipEmptyParts);
    
    foreach (QString str, strList)
    {
        for (int i = 0; i < amountFields; i++)
        {
            reGlobal.setPattern("^" + fieldID[i] + "(.*)");
//            cout << "pattern: " << re.pattern().toLatin1().data() <<
//                 "\nstring: " << str.toLatin1().data() << endl;
            if (reGlobal.indexIn(str)!= -1)
            {
                // вставляем идентификатор следующего поля
                clearedData.push_back(fieldID[i]);
                clearedData.push_back(reGlobal.cap(1));
                break;
            }
        }
    }

    for (unsigned short int i = 0; i < clearedData.size(); i++)
    {
        if (clearedData.at(i) == "10#")
            finalData.append("<b>Фамилия:</b> " + clearedData.at(++i) + "<br>");
        else
        if (clearedData.at(i) == "11#")
            finalData.append("<b>Имя:</b> " + clearedData.at(++i) + "<br>");
        else
        if (clearedData.at(i) == "12#")
            finalData.append("<b>Отчество:</b> " + clearedData.at(++i) + "<br>");
        else
        if (clearedData.at(i) == "21#")
            finalData.append("<b>Год Рождения:</b> " + clearedData.at(++i) + "<br>");
        else
        if (clearedData.at(i) == "50#")
            finalData.append("<b>Категория:</b> " + clearedData.at(++i) + "<br>");
        else
        if (clearedData.at(i) == "67#")
            finalData.append("<b>Доп. категория:</b> " + clearedData.at(++i) + "<br>");
        else
        if (clearedData.at(i) == "20#")
            finalData.append("<b>Образование:</b> " + clearedData.at(++i) + "<br>");
        else
        if (clearedData.at(i) == "17#")
            finalData.append("<b>Телефон:</b> " + clearedData.at(++i) + "<br>");
        else
            finalData.append(clearedData.at(i) + "<br>");
        
        
    }
    
    
    cout << "end parsing" << endl;
    return finalData;
}
コード例 #11
0
void
dmz::QtPluginAppUpdater::_slot_download_start () {

    if (_updateDialog) {

#if defined (Q_WS_WIN)
        const QString FileType ("exe");
#elif defined (Q_WS_MAC)
        const QString FileType ("dmg");
#else
        const QString FileType ("zip");
#endif

        QString appName (_updateVersion.get_name ().get_buffer ());
        appName.replace (" ", "-");

        const String Major (_updateVersion.get_major ());
        const String Minor (_updateVersion.get_minor ());
        const String Bug (_updateVersion.get_bug ());
        const String Build (_updateVersion.get_build ());

        QString fileName;

        if (_downloadToTemp) {

            fileName = tr ("%1/%2-%3-%4-%5-%6.%7").
                       arg (QDir::tempPath ()).
                       arg (appName).
                       arg (Major.get_buffer ()).
                       arg (Minor.get_buffer ()).
                       arg (Bug.get_buffer ()).
                       arg (Build.get_buffer ()).
                       arg (FileType);
        }
        else {

            QString defaultFileName = tr ("%1/%2-%3-%4-%5-%6.%7").
                                      arg (QDesktopServices::storageLocation (QDesktopServices::DesktopLocation)).
                                      arg (appName).
                                      arg (Major.get_buffer ()).
                                      arg (Minor.get_buffer ()).
                                      arg (Bug.get_buffer ()).
                                      arg (Build.get_buffer ()).
                                      arg (FileType);

#if defined (Q_WS_MAC)
            QString tempPath (defaultFileName);

            tempPath.replace (QRegExp (
                                  QDesktopServices::displayName (QDesktopServices::DesktopLocation)),
                              "Downloads");

            QFileInfo fi (tempPath);

            if (QFile::exists (fi.absolutePath ())) {
                defaultFileName = tempPath;
            }
#endif

            fileName = get_save_file_name_with_extension (
                           _mainWindowModule ? _mainWindowModule->get_qt_main_window () : 0,
                           tr ("Save File"),
                           QDir::toNativeSeparators (defaultFileName),
                           tr ("*.%1").arg (FileType),
                           FileType);
        }

        if (!fileName.isEmpty ()) {

            QString downloadServer (_downloadUrl.get_buffer ());
            downloadServer.replace ("{app_name}", appName);
            downloadServer.replace ("{major}", Major.get_buffer ());
            downloadServer.replace ("{minor}", Minor.get_buffer ());
            downloadServer.replace ("{bug}", Bug.get_buffer ());
            downloadServer.replace ("{build_number}", Build.get_buffer ());
            downloadServer.append (tr (".") + FileType);

            QUrl url (downloadServer);

            _log.info << "Downloading: " << qPrintable (url.toString ()) << endl;

            QNetworkRequest request (url);

            _downloadReply = _netManager->get (request);

            if (_downloadReply) {

                connect (
                    _downloadReply, SIGNAL (downloadProgress (qint64, qint64)),
                    this, SLOT (_slot_download_progress (qint64, qint64)));

                connect (
                    _downloadReply, SIGNAL (readyRead ()),
                    this, SLOT (_slot_download_ready_read ()));

                connect (
                    _downloadReply, SIGNAL (finished ()),
                    this, SLOT (_slot_download_finished ()));

                _downloadFile.setFileName (fileName);
            }

            if (!_downloadFile.open (QIODevice::WriteOnly)) {

                _log.warn << "Failed to open file for download. Download aborted!" << endl;

                if (_downloadReply) {
                    _downloadReply->abort ();
                }

                QMessageBox::warning (
                    _updateDialog->parentWidget (),
                    "Update Failed",
                    "Failed to open temp file for download.\nDownload aborted!");

                _updateDialog->reject ();
            }
            else {

                _ui.stackedWidget->setCurrentWidget (_ui.downloadPage);
            }
        }
    }
}
コード例 #12
0
void QgsDiagramSettings::writeXML( QDomElement& rendererElem, QDomDocument& doc ) const
{
  QDomElement categoryElem = doc.createElement( "DiagramCategory" );
  categoryElem.setAttribute( "font", font.toString() );
  categoryElem.setAttribute( "backgroundColor", backgroundColor.name() );
  categoryElem.setAttribute( "backgroundAlpha", backgroundColor.alpha() );
  categoryElem.setAttribute( "width", QString::number( size.width() ) );
  categoryElem.setAttribute( "height", QString::number( size.height() ) );
  categoryElem.setAttribute( "penColor", penColor.name() );
  categoryElem.setAttribute( "penAlpha", penColor.alpha() );
  categoryElem.setAttribute( "penWidth", QString::number( penWidth ) );
  categoryElem.setAttribute( "minScaleDenominator", QString::number( minScaleDenominator ) );
  categoryElem.setAttribute( "maxScaleDenominator", QString::number( maxScaleDenominator ) );
  categoryElem.setAttribute( "transparency", QString::number( transparency ) );

  // site type (mm vs. map units)
  if ( sizeType == MM )
  {
    categoryElem.setAttribute( "sizeType", "MM" );
  }
  else
  {
    categoryElem.setAttribute( "sizeType", "MapUnits" );
  }

  // label placement method (text diagram)
  if ( labelPlacementMethod == Height )
  {
    categoryElem.setAttribute( "labelPlacementMethod", "Height" );
  }
  else
  {
    categoryElem.setAttribute( "labelPlacementMethod", "XHeight" );
  }

  if ( scaleByArea )
  {
    categoryElem.setAttribute( "scaleDependency", "Area" );
  }
  else
  {
    categoryElem.setAttribute( "scaleDependency", "Diameter" );
  }

  // orientation (histogram)
  switch ( diagramOrientation )
  {
    case Left:
      categoryElem.setAttribute( "diagramOrientation", "Left" );
      break;

    case Right:
      categoryElem.setAttribute( "diagramOrientation", "Right" );
      break;

    case Down:
      categoryElem.setAttribute( "diagramOrientation", "Down" );
      break;

    case Up:
      categoryElem.setAttribute( "diagramOrientation", "Up" );
      break;

    default:
      categoryElem.setAttribute( "diagramOrientation", "Up" );
      break;
  }

  categoryElem.setAttribute( "barWidth", QString::number( barWidth ) );
  categoryElem.setAttribute( "minimumSize", QString::number( minimumSize ) );
  categoryElem.setAttribute( "angleOffset", QString::number( angleOffset ) );

  QString colors;
  for ( int i = 0; i < categoryColors.size(); ++i )
  {
    if ( i > 0 )
    {
      colors.append( "/" );
    }
    colors.append( categoryColors.at( i ).name() );
  }
  categoryElem.setAttribute( "colors", colors );

  QString categories;
  for ( int i = 0; i < categoryIndices.size(); ++i )
  {
    if ( i > 0 )
    {
      categories.append( "/" );
    }
    categories.append( QString::number( categoryIndices.at( i ) ) );
  }
  categoryElem.setAttribute( "categories", categories );

  rendererElem.appendChild( categoryElem );
}
コード例 #13
0
void ccRasterizeTool::generateImage() const
{
	if (!m_grid.isValid())
		return;

	//default values
	double emptyCellsHeight = 0;
	double minHeight = m_grid.minHeight;
	double maxHeight = m_grid.maxHeight;
	//get real values
	EmptyCellFillOption fillEmptyCellsStrategy = getFillEmptyCellsStrategyExt(	emptyCellsHeight,
																				minHeight,
																				maxHeight);

	QImage bitmap8(m_grid.width,m_grid.height,QImage::Format_Indexed8);
	if (!bitmap8.isNull())
	{
		// Build a custom palette (gray scale)
		QVector<QRgb> palette(256);
		{
			for (unsigned i = 0; i < 256; i++)
				palette[i] = qRgba(i,i,i,255);
		}
		double maxColorComp = 255.99; //.99 --> to avoid round-off issues later!

		if (fillEmptyCellsStrategy == LEAVE_EMPTY)
		{
			palette[255] = qRgba(255,0,255,0); //magenta/transparent color for empty cells (in place of pure white)
			maxColorComp = 254.99;
		}

		bitmap8.setColorTable(palette);
		//bitmap8.fill(255);

		unsigned emptyCellColorIndex = 0;
		switch (fillEmptyCellsStrategy)
		{
		case LEAVE_EMPTY:
			emptyCellColorIndex = 255; //should be transparent!
			break;
		case FILL_MINIMUM_HEIGHT:
			emptyCellColorIndex = 0;
			break;
		case FILL_MAXIMUM_HEIGHT:
			emptyCellColorIndex = 255;
			break;
		case FILL_CUSTOM_HEIGHT:
			{
				double normalizedHeight = (emptyCellsHeight-minHeight)/(maxHeight-minHeight);
				//min and max should have already been updated with custom empty cell height!
				assert(normalizedHeight >= 0.0 && normalizedHeight <= 1.0);
				emptyCellColorIndex = static_cast<unsigned>(floor(normalizedHeight*maxColorComp));
			}
			break;
		case FILL_AVERAGE_HEIGHT:
		default:
			assert(false);
		}

		double range = maxHeight - minHeight;
		if (range < ZERO_TOLERANCE)
			range = 1.0;

		// Filling the image with grid values
		for (unsigned j=0; j<m_grid.height; ++j)
		{
			const RasterCell* aCell = m_grid.data[j];
			for (unsigned i=0; i<m_grid.width; ++i,++aCell)
			{
				if (aCell->h == aCell->h)
				{
					double normalizedHeight = (aCell->h - minHeight)/range;
					assert(normalizedHeight >= 0.0 && normalizedHeight <= 1.0);
					unsigned char val = static_cast<unsigned char>(floor(normalizedHeight*maxColorComp));
					bitmap8.setPixel(i,m_grid.height-1-j,val);
				}
				else //NaN
				{
					bitmap8.setPixel(i,m_grid.height-1-j,emptyCellColorIndex);
				}
			}
		}

		//open file saving dialog
		{
			//add images output file filters
			QString filters;

			//we grab the list of supported image file formats (writing)
			QList<QByteArray> formats = QImageWriter::supportedImageFormats();
			if (formats.empty())
			{
				ccLog::Error("No image format supported by your system?!\n(check that the 'imageformats' directory is alongside CC executable)");
			}
			else
			{
				//we convert this list into a proper "filters" string
				for (int i=0; i<formats.size(); ++i)
					filters.append(QString("%1 image (*.%2)\n").arg(QString(formats[i].data()).toUpper()).arg(formats[i].data()));

				QSettings settings;
				settings.beginGroup(ccPS::HeightGridGeneration());
				QString imageSavePath = settings.value("savePathImage",QApplication::applicationDirPath()).toString();
				QString outputFilename = QFileDialog::getSaveFileName(0,"Save raster image",imageSavePath+QString("/raster_image.%1").arg(formats[0].data()),filters);

				if (!outputFilename.isNull())
				{
					if (bitmap8.save(outputFilename))
					{
						ccLog::Print(QString("[Rasterize] Image '%1' succesfully saved").arg(outputFilename));
						//save current export path to persistent settings
						settings.setValue("savePathImage",QFileInfo(outputFilename).absolutePath());
					}
					else
					{
						ccLog::Error("Failed to save image file!");
					}
				}
			}
		}
	}
	else
	{
		ccLog::Error("Failed to create output image! (not enough memory?)");
	}
}
コード例 #14
0
ファイル: main.cpp プロジェクト: almak96/AppCore
void convertString()
{
    //int interval;
    int dayN = 0;
   while(dayN<sizeDay) {
        for(int i = 0; i<fileString.size();i++)
        {
            switch (fileString.at(i).toLatin1())
            {
                case '|':
                    day[dayN].chetnost = true;
                break;


                case '_':
                    day[dayN].chetnost = false;
                 break;

                case '^':{

                    QString buff;
                    bool ok = false;
                    buff = fileString.at(i+1);
                    day[dayN].numberDay = buff.toInt(&ok, 10);
                    i++;
                    break;
                    }


            case '&':{
                i++;
                QString buff;
                    while(fileString.at(i).toLatin1()!=35)//56 90  97 112
                    {

                        buff.append(fileString.at(i));
                        //interval++;
                        if(fileString.at(i+1).toLatin1()==35)
                        {
                            day[dayN].numberClass.append(fileString.at(i+2));
                            day[dayN].classes.append(buff);

                        }
                        i++;
                    }

                    i++;
                break;
                    }
                case ';':
                        dayN++;
                break;
            default:
                //interval = 5;
                break;




         }
        }
    }

}
コード例 #15
0
ファイル: sendcoinsdialog.cpp プロジェクト: Cloudsy/bitcoin
void SendCoinsDialog::on_sendButton_clicked()
{
    if(!model || !model->getOptionsModel())
        return;

    QList<SendCoinsRecipient> recipients;
    bool valid = true;

    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            if(entry->validate())
            {
                recipients.append(entry->getValue());
            }
            else
            {
                valid = false;
            }
        }
    }

    if(!valid || recipients.isEmpty())
    {
        return;
    }

    fNewRecipientAllowed = false;
    WalletModel::UnlockContext ctx(model->requestUnlock());
    if(!ctx.isValid())
    {
        // Unlock wallet was cancelled
        fNewRecipientAllowed = true;
        return;
    }

    // prepare transaction for getting txFee earlier
    WalletModelTransaction currentTransaction(recipients);
    WalletModel::SendCoinsReturn prepareStatus;
    if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled
        prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl);
    else
        prepareStatus = model->prepareTransaction(currentTransaction);

    // process prepareStatus and on error generate message shown to user
    processSendCoinsReturn(prepareStatus,
        BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()));

    if(prepareStatus.status != WalletModel::OK) {
        fNewRecipientAllowed = true;
        return;
    }

    CAmount txFee = currentTransaction.getTransactionFee();

    // Format confirmation message
    QStringList formatted;
    Q_FOREACH(const SendCoinsRecipient &rcp, currentTransaction.getRecipients())
    {
        // generate bold amount string
        QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
        amount.append("</b>");
        // generate monospace address string
        QString address = "<span style='font-family: monospace;'>" + rcp.address;
        address.append("</span>");

        QString recipientElement;

        if (!rcp.paymentRequest.IsInitialized()) // normal payment
        {
            if(rcp.label.length() > 0) // label with address
            {
                recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
                recipientElement.append(QString(" (%1)").arg(address));
            }
            else // just address
            {
                recipientElement = tr("%1 to %2").arg(amount, address);
            }
        }
        else if(!rcp.authenticatedMerchant.isEmpty()) // authenticated payment request
        {
            recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
        }
        else // unauthenticated payment request
        {
            recipientElement = tr("%1 to %2").arg(amount, address);
        }

        formatted.append(recipientElement);
    }

    QString questionString = tr("Are you sure you want to send?");
    questionString.append("<br /><br />%1");

    if(txFee > 0)
    {
        // append fee string if a fee is required
        questionString.append("<hr /><span style='color:#aa0000;'>");
        questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee));
        questionString.append("</span> ");
        questionString.append(tr("added as transaction fee"));

        // append transaction size
        questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)");
    }

    // add total amount in all subdivision units
    questionString.append("<hr />");
    CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
    QStringList alternativeUnits;
    Q_FOREACH(BitcoinUnits::Unit u, BitcoinUnits::availableUnits())
    {
        if(u != model->getOptionsModel()->getDisplayUnit())
            alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
    }
    questionString.append(tr("Total Amount %1 (= %2)")
        .arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount))
        .arg(alternativeUnits.join(" " + tr("or") + " ")));

    QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
        questionString.arg(formatted.join("<br />")),
        QMessageBox::Yes | QMessageBox::Cancel,
        QMessageBox::Cancel);

    if(retval != QMessageBox::Yes)
    {
        fNewRecipientAllowed = true;
        return;
    }

    // now send the prepared transaction
    WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction);
    // process sendStatus and on error generate message shown to user
    processSendCoinsReturn(sendStatus);

    if (sendStatus.status == WalletModel::OK)
    {
        accept();
        CoinControlDialog::coinControl->UnSelectAll();
        coinControlUpdateLabels();
    }
    fNewRecipientAllowed = true;
}
コード例 #16
0
ファイル: logloader.cpp プロジェクト: djandruczyk/emstune
void LogLoader::run()
{
	QFile logfile(m_filename);
	logfile.open(QIODevice::ReadOnly);
	//QByteArray arr = logfile.readAll();

	//logfile.close();
	int curr = 0;
	//bool escape = false;
	bool inpacket = false;
	QByteArray currPacket;
	//while (!escape || curr >= arr.size())
	QByteArray retval;
	while (!logfile.atEnd())
	{
		//logfile.read(&retval,1);
		emit logProgress(logfile.pos(),logfile.size());
		retval = logfile.read(1);
		if (retval[0] == (char)0xAA)
		{
			if (inpacket)
			{
				//in the middle of a packet
				currPacket.clear();
			}
			currPacket.append(retval[0]);
			//Start byte
			//qDebug() << "Start byte";
			inpacket = true;
		}
		else if (retval[0] == (char)0xCC)
		{
			//currPacket
			currPacket.append(retval[0]);
			QString output;
			for (int i=0;i<currPacket.size();i++)
			{
				int num = (unsigned char)currPacket[i];
				output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
			}
            qDebug() << "Full packet:";
			//qDebug() << output;

			parseBuffer(currPacket);
			currPacket.clear();
			//qDebug() << "loop";
			msleep(25);
		}
		else if (inpacket)
		{
			if (retval[0] == (char)0xBB)
			{
				//Need to escape the next byte
				retval = logfile.read(1);
				if (retval[0] == (char)0x55)
				{
					currPacket.append((char)0xAA);
				}
				else if (retval[0] == (char)0x44)
				{
					currPacket.append((char)0xBB);
				}
				else if (retval[0] == (char)0x33)
				{
					currPacket.append((char)0xCC);
				}
			}
			else
			{
				currPacket.append(retval[0]);
			}
		}
		curr++;
	}
	emit endOfLog();
	logfile.close();
	return;
	/*for (int i=0;i<arr.size();i++)
	{
		//i++;
		//qDebug() << QString::number(arr[i],16);
		curr = i;

		curr+=3;
		curr += 1;
		i += curr-1;
		//i++;

	}*/
}
コード例 #17
0
ファイル: serialthread.cpp プロジェクト: DeuceEFI/emstudio
void SerialThread::run()
{
	if (openPort(m_portName,m_baud))
	{
		qDebug() << "Error opening com port";
		return;
	}
	//m_logFile = new QFile(m_logFileName);
	//m_logFile->open(QIODevice::ReadWrite | QIODevice::Truncate);
	unsigned char buffer[1024];
	int readlen = 0;
	QByteArray qbuffer;
	bool inpacket= false;
	bool inescape=true;
	while (true)
	{
#ifdef Q_OS_WIN32
		if (!ReadFile(m_portHandle,(LPVOID)buffer,1024,(LPDWORD)&readlen,NULL))
		{
			//Serial error here
			qDebug() << "Serial Read error";
		}
#else
		readlen = read(m_portHandle,buffer,1024);
#endif //Q_OS_WIN32
		if (readlen == 0)
		{
			msleep(10);
		}
		else if (readlen == -1)
		{
			qDebug() << "Serial Read error";
		}
		for (int i=0;i<readlen;i++)
		{
			if (buffer[i] == 0xAA)
			{
				if (inpacket)
				{
					//Start byte in the middle of a packet
					//Clear out the buffer and start fresh
					inescape = false;
					qbuffer.clear();
				}
				qbuffer.append(buffer[i]);
				//qDebug() << "Start of packet";
				//Start of packet
				inpacket = true;
			}
			else if (buffer[i] == 0xCC && inpacket)
			{
				//qDebug() << "End of packet. Size:" << qbuffer.size();
				//End of packet
				inpacket = false;
				qbuffer.append(buffer[i]);
				//m_logFile->write(qbuffer);
				//m_logFile->flush();
				emit parseBuffer(qbuffer);
				QString output;
				for (int i=0;i<qbuffer.size();i++)
				{
					int num = (unsigned char)qbuffer[i];
					output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
				}
				//qDebug() << "Full packet:";
				//qDebug() << output;
				qbuffer.clear();
			}
			else
			{
				if (inpacket && !inescape)
				{
					if (buffer[i] == 0xBB)
					{
						//Need to escape the next byte
						//retval = logfile.read(1);
						inescape = true;
					}
					else
					{
						qbuffer.append(buffer[i]);
					}

				}
				else if (inpacket && inescape)
				{
					if (buffer[i] == 0x55)
					{
						qbuffer.append((char)0xAA);
					}
					else if (buffer[i] == 0x44)
					{
						qbuffer.append((char)0xBB);
					}
					else if (buffer[i] == 0x33)
					{
						qbuffer.append((char)0xCC);
					}
					inescape = false;
				}
			}
		}
	}
}
コード例 #18
0
ファイル: OSItemList.cpp プロジェクト: ChengXinDL/OpenStudio
OSItemList::OSItemList(OSVectorController* vectorController,
                       bool addScrollArea,
                       QWidget * parent)
  : OSItemSelector(parent),
    m_vectorController(vectorController),
    m_vLayout(nullptr),
    m_selectedItem(nullptr),
    m_itemsDraggable(false),
    m_itemsRemoveable(false),
    m_type(OSItemType::ListItem),
    m_dirty(false)
{
  // for now we will allow this item list to manage memory of 
  OS_ASSERT(!m_vectorController->parent());
  m_vectorController->setParent(this);

  this->setObjectName("GrayWidget"); 

  QString style;

  style.append("QWidget#GrayWidget {");
  style.append(" background: #E6E6E6;");
  style.append(" border-bottom: 1px solid black;");
  style.append("}");

  setStyleSheet(style);

  QVBoxLayout* outerVLayout = new QVBoxLayout();
  outerVLayout->setContentsMargins(0,0,0,0);
  this->setLayout(outerVLayout);

  QWidget* outerWidget = new QWidget();

  if (addScrollArea){
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setFrameStyle(QFrame::NoFrame);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    outerVLayout->addWidget(scrollArea);
    scrollArea->setWidget(outerWidget);
    scrollArea->setWidgetResizable(true);
  }else{
    outerVLayout->addWidget(outerWidget);
  }

  m_vLayout = new QVBoxLayout();
  outerWidget->setLayout(m_vLayout);
  m_vLayout->setContentsMargins(0,0,0,0);
  m_vLayout->setSpacing(0);
  m_vLayout->addStretch();

  connect(this, &OSItemList::itemsRequested, vectorController, &OSVectorController::reportItems);

  /* Vector controller does not handle removing items in list from model
  *
  connect(this, &OSItemList::itemRemoveClicked, vectorController, &OSVectorController::removeItem);
  */

  connect(vectorController, &OSVectorController::itemIds, this, &OSItemList::setItemIds);

  connect(vectorController, &OSVectorController::selectedItemId, this, &OSItemList::selectItemId);

  // allow time for OSDocument to finish constructing
  QTimer::singleShot(0, vectorController, SLOT(reportItems()));
}
コード例 #19
0
ファイル: mainwindow.cpp プロジェクト: Grandge/KanmusuMemory
void MainWindow::handleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
    QString str = tr("Handle ssl errors.\nDo you want to continue on an understanding of the security risk?\n");
    foreach (QSslError e, errors){
        str.append("ssl error: " + e.errorString());
    }
コード例 #20
0
ファイル: samplerbank.cpp プロジェクト: Alppasa/mixxx
void SamplerBank::slotSaveSamplerBank(double v) {
    if (v == 0.0 || m_pPlayerManager == NULL) {
        return;
    }
    QString filefilter = tr("Mixxx Sampler Banks (*.xml)");
    QString samplerBankPath = QFileDialog::getSaveFileName(
            NULL, tr("Save Sampler Bank"),
            QString(),
            tr("Mixxx Sampler Banks (*.xml)"),
            &filefilter);
    if (samplerBankPath.isNull() || samplerBankPath.isEmpty()) {
        return;
    }
    // Manually add extension due to bug in QFileDialog
    // via https://bugreports.qt-project.org/browse/QTBUG-27186
    // Can be removed after switch to Qt5
    QFileInfo fileName(samplerBankPath);
    if (fileName.suffix().isEmpty()) {
        QString ext = filefilter.section(".",1,1);
        ext.chop(1);
        samplerBankPath.append(".").append(ext);
    }

    // The user has picked a new directory via a file dialog. This means the
    // system sandboxer (if we are sandboxed) has granted us permission to this
    // folder. We don't need access to this file on a regular basis so we do not
    // register a security bookmark.

    QFile file(samplerBankPath);
    if (!file.open(QIODevice::WriteOnly)) {
        QMessageBox::warning(NULL,
                             tr("Error Saving Sampler Bank"),
                             tr("Could not write the sampler bank to '%1'.")
                             .arg(samplerBankPath));
        return;
    }

    QDomDocument doc("SamplerBank");

    QDomElement root = doc.createElement("samplerbank");
    doc.appendChild(root);

    for (unsigned int i = 0; i < m_pPlayerManager->numSamplers(); ++i) {
        Sampler* pSampler = m_pPlayerManager->getSampler(i + 1);
        if (pSampler == NULL) {
            continue;
        }
        QDomElement samplerNode = doc.createElement(QString("sampler"));

        samplerNode.setAttribute("group", pSampler->getGroup());

        TrackPointer pTrack = pSampler->getLoadedTrack();
        if (pTrack) {
            QString samplerLocation = pTrack->getLocation();
            samplerNode.setAttribute("location", samplerLocation);
        }
        root.appendChild(samplerNode);
    }

    QString docStr = doc.toString();

    file.write(docStr.toUtf8().constData());
    file.close();
}
コード例 #21
0
ファイル: qglimagegpuwidget.cpp プロジェクト: mwerlberger/imp
//-----------------------------------------------------------------------------
void QGLImageGpuWidget::mouseMoveEvent(QMouseEvent * event)
{
  this->makeCurrent();

  mouse_x_ = floor(event->x()/zoom_);
  mouse_y_ = floor(event->y()/zoom_);

  if (button_ == Qt::LeftButton)
    emit mouseMoved(mouse_x_old_, mouse_y_old_, mouse_x_, mouse_y_);
  else if (button_ == Qt::MidButton)
    emit pan(mouse_x_old_*zoom_, mouse_y_old_*zoom_, mouse_x_*zoom_, mouse_y_*zoom_);

  mouse_x_old_ = mouse_x_;
  mouse_y_old_ = mouse_y_;

  if ((mouse_x_ > 0) && (mouse_y_>0) && (mouse_x_<static_cast<int>(image_->width())) && (mouse_y_<static_cast<int>(image_->height())))
  {
    QString text = "Pixel info: (";
    QString xpos;
    xpos.setNum(mouse_x_);
    QString ypos;
    ypos.setNum(mouse_y_);
    text.append(xpos).append(", ").append(ypos).append(")=");

    if(bit_depth_ == 8)
    {
      if(num_channels_ == 1) // uchar
      {
        unsigned char value = reinterpret_cast<iu::ImageGpu_8u_C1*>(image_)->getPixel(mouse_x_, mouse_y_);
        QString val;
        val.setNum(value);
        text.append(val);
      }
      else // uchar4
      {
        uchar4 value = reinterpret_cast<iu::ImageGpu_8u_C4*>(image_)->getPixel(mouse_x_, mouse_y_);
        QString rval;
        rval.setNum(value.x );
        text.append("<font color=#990000>").append(rval).append("</font>, ");
        QString gval;
        gval.setNum(value.y);
        text.append("<font color=#009900>").append(gval).append("</font>, ");
        QString bval;
        bval.setNum(value.z);
        text.append("<font color=#000099>").append(bval).append("</font>, ");
        QString alphaval;
        alphaval.setNum(value.w);
        text.append("<font color=#666666>").append(alphaval).append("</font>");
      }
    }
    else
    {
      if(num_channels_ == 1) // float
      {
        float value = reinterpret_cast<iu::ImageGpu_32f_C1*>(image_)->getPixel(mouse_x_, mouse_y_);
        QString val;
        val.setNum(value, 'g', 3 );
        text.append(val);
      }
      else // float4
      {
        float4 value = reinterpret_cast<iu::ImageGpu_32f_C4*>(image_)->getPixel(mouse_x_, mouse_y_);
        QString rval;
        rval.setNum(value.x, 'g', 3 );
        text.append("<font color=#990000>").append(rval).append("</font>, ");
        QString gval;
        gval.setNum(value.y, 'g', 3);
        text.append("<font color=#009900>").append(gval).append("</font>, ");
        QString bval;
        bval.setNum(value.z, 'g', 3);
        text.append("<font color=#000099>").append(bval).append("</font>, ");
        QString alphaval;
        alphaval.setNum(value.w, 'g', 3);
        text.append("<font color=#666666>").append(alphaval).append("</font>");
      }
    }

    emit pixelInfo(text);
  }
}
コード例 #22
0
ファイル: qtBuiltins.cpp プロジェクト: jjinux/jenarix
QString obout( QObject *w) {
  QString attr; // return value

  QString wname = w->objectName();
  QString wtype = w->metaObject()->className();
  //qDebug() << wname << wtype;

  if (OUTXML) {
    //printf("<%s>\n", wname.replace(' ','_').toAscii().data());
    jxout += "<" + wname.replace(' ','_') + " >\n";
    return wname;
  }

  QString outname;
/* eliminate cruft */
  if (wname.startsWith("qt_")) {
  } else if (wname.isNull()) {
    if (wtype == "QWidget") {
    } else if (wtype == "QSplitterHandle") {
    } else if (wtype == "QTextControl") {
    } else if (wtype == "QVBoxLayout") {
    } else if (wtype == "QAction") {
    }

  } else if (wname == "VSplitter") {
    outname = wname;
    attr = " ";
  } else if (wname == "HSplitter") {
    outname = wname;
    attr = " ";
  } else if (wname == "MenuBar") {
    outname = wname;
    attr = " ";
  } else if (wname == "MenuItem") {
    outname = wname;
    attr = " ";
  } else if (wname == "Navigator") {
    outname = wname;
    attr = " ";
  } else if (wname == "Widget") {
    outname = wname;
    attr = " ";
  } else if (wname == "OpenGLContext") {
    outname = wname;
    attr = " ";
  } else if (wtype == "QMenu") {
    outname = "MenuItem";
    attr = "label: "; attr.append('"'); attr.append(wname); attr.append('"');
  } else if (wtype == "QAction") {
    outname = "MenuItem";
    attr = "label: "; attr.append('"'); attr.append(wname); attr.append('"');
    QString check = check_attr((QAction *)w);
    if (!check.isNull()) attr.append(","+check);
  } else if (wtype == "JXAction") {
    outname = "MenuItem";
    attr = "label: "; attr.append('"'); attr.append(wname); attr.append('"');
    QString cback = callback_attr((JXAction *)w);
    if (!cback.isNull()) attr.append(","+cback);
    QString check = check_attr((QAction *)w);
    if (!check.isNull()) attr.append(","+check);
  } else {
    attr = " ";
  }

  if (!outname.isNull()) {
    //printf("(%s [\n", outname.toAscii().data());
    jxout += "( " + outname + " [\n";
  }
  return attr;

}
コード例 #23
0
ファイル: myprint.cpp プロジェクト: kanbodows/kafpocs
QString MyPrint::printOnlyTable(QSqlQueryModel *model, RowList colHeaders, int groupCols)
{
    QString body;
    QStringList colls;
    body.append("<table border='1' class = 'mine'><tr>");
    RowList::const_iterator i = colHeaders.constBegin();
    while (i != colHeaders.constEnd()) {
        colls.append(QString::number(i.key()));
        body.append("<th>" + i.value() + "</th>\n");
        ++i;
    }
    body.append("</tr>\n");
    while (model->canFetchMore())
        model->fetchMore();
    QMap<int,QString> groupTitles; // заголовки групп groupTitles(номер колонки, название группы)
    QMap<int,int> groupCounts; // количество элементов в группе groupCounts(номер колонки, кол-во)
    for (int index = 0; index < model->rowCount(); index++)
    {
        body.append("<tr>\n");
        for (int listId = 0; listId < colls.count(); listId++)
        {
            if(listId < groupCols) // если колонки нужно сгруппировать(если это групируемая колонка)
            {
                if(groupTitles.value(listId) != model->record(index).value(colls[listId].toInt()).toString())
                {
                    groupTitles[listId] = model->record(index).value(colls[listId].toInt()).toString();
                    body.append("<td class='grHead' colspan = '"+QString::number(colls.count()-listId)+"'><b>");
                    body.append(groupTitles[listId]);
                    body.append("</b></td>\n</tr>\n<tr>\n");
                    if(listId == groupCols-1)
                        for(int i=0; i < listId + 1; i++)
                            body.append("<td>1</td>\n");
                    else
                        for(int i=0; i < listId + 1; i++)
                            body.append("<td></td>\n");
                    groupCounts[listId] = 1;
                }
                else
                {
                    groupCounts[listId] = groupCounts[listId] + 1;
                    body.append("<td>" + QString::number(groupCounts[listId]) + "</td>\n");
                }
            }
            else
            {
                body.append("<td>");
                body.append(model->record(index).value(colls[listId].toInt()).toString());
                body.append("</td>\n");
            }
        }
        body.append("</tr>\n");
    }
    body.append("</table>");
    return body;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: osamanagib/UkooaFix
int main(int argc, char *argv[])
{

    //  QGuiApplication a(argc, argv);
    QApplication a(argc, argv);
    QwtPlot *plot = new QwtPlot();
    QwtPlotCanvas *canvas = new QwtPlotCanvas();
    canvas->setBorderRadius(10);

    plot->setCanvas(canvas);
    plot->setCanvasBackground(QColor("LIGHTGRAY"));

    plot->enableAxis(QwtPlot::yRight);
    plot->enableAxis(QwtPlot::xTop);
    plot->setAxisTitle(QwtPlot::xBottom, "Xline");
    plot->setAxisTitle(QwtPlot::xTop, "Xline");
    plot->setAxisTitle(QwtPlot::yLeft, "Inline");
    plot->setAxisTitle(QwtPlot::yRight, "Inline");
    //    float minx = srv->getStations().first().x();
    //    float maxx = srv->getStations().last().x();
        plot->setAxisScale( QwtPlot::xBottom,3500,300);
    //    plot->setAxisScale( QwtPlot::xTop,minx,maxx );
    //    QwtScaleDraw *sd = axisScaleDraw( QwtPlot::yLeft );
    //    sd->setMinimumExtent( sd->extent( axisWidget( QwtPlot::yLeft )->font() ) );
    plot->plotLayout()->setAlignCanvasToScales( true );
    QFileDialog custDialog;
    QStringList names = custDialog.getOpenFileNames(NULL, ("Open Files..."),QString(), ("UKOOA Files (*.p190 *.p90);;All Files (*)"));

    // handle if the dialog was "Cancelled"
    if(names.isEmpty())
    {
        return 0;
    }
    qSort(names.begin(), names.end());
    QVector <QwtPlotCurve *> curves;
    foreach (QString name, names)
    {


        QwtPlotCurve *vCurve = new QwtPlotCurve;
       if(name.contains(QString( "NS1763")) || name.contains(QString("NS2029")))
        {
           QColor c = Qt::red;
            vCurve->setSymbol( new QwtSymbol( QwtSymbol::Ellipse, Qt::red,c , QSize( 2, 2 ) ) );
        }
        else
        {
           QColor c = Qt::green;
            vCurve->setSymbol( new QwtSymbol( QwtSymbol::Ellipse, Qt::green,c , QSize( 2, 2 ) ) );
        }
        vCurve->setStyle( QwtPlotCurve::NoCurve );
        vCurve->setPen( Qt::gray );

        cout << name.toStdString() << endl;
        QVector<QPointF> curveData;

        //  m_nameLineLable->setText(m_names.at(0));
        QFile *ukFile = new QFile(QString(name));

        bool rt = ukFile->open(QIODevice::ReadOnly);

        cout << "return " << rt << endl;

        qint64 icount = 0;

        qint64 fileSize = ukFile->size();
        char *data = new char[fileSize];
        ukFile->read(data,fileSize);
        QString sData = data;
        QString shot = "SNS";
        while (true)
        {
            ukFile->seek(icount);
            ukFile->read(data,fileSize);
            sData = data;;
            if(icount>=fileSize)
            {
                break;
            }
            auto sPos = sData.indexOf(shot,0,Qt::CaseInsensitive);
            QString cr = sData.mid(sPos,19);
            if(cr.contains("\n"))
            {
                sPos +=2;
            }
            // auto shotNo  = sData.mid(sPos+20,sPos+5);
            QString shotNo = sData.mid(sPos+19,6);
            int shotNos;

            if(shotNo.contains("\n") || shotNo.contains("\r"))
            {
                shotNo = sData.mid(sPos+19,8);
                int shift1 = shotNo.indexOf("\r");
                int shift = shotNo.indexOf("\n");
                //    cout << shift1 << " " << shift << endl;
                QString tmp = shotNo.mid(0,shift1);
                tmp.append(shotNo.mid(shift+1,3));
                shotNos = tmp.toInt();
            }
            else
            {
                shotNos = sData.mid(sPos+19,6).toInt();
            }

            float shotYs;
            sPos = sData.indexOf(shot,0,Qt::CaseInsensitive);
            cr = sData.mid(sPos,55);
            if(cr.contains("\n"))
            {
                //       cout << " cr " << sPos << endl;
                sPos +=2;
            }

            QString shotY = sData.mid(sPos+55,10);
            //   cout << "shotx " << shotX.toStdString() << endl;
            if(shotY.contains("\n") || shotY.contains("\r"))
            {
                shotY = sData.mid(sPos+55,12);
                int shift1 = shotY.indexOf("\r");
                int shift = shotY.indexOf("\n");
                //           cout << shift1 << " " << shift << endl;
                QString tmp = shotY.mid(0,shift1);
                tmp.append(shotY.mid(shift+1,12));
                shotYs = tmp.toFloat();
            }
            else
            {
                shotYs = shotY.toFloat();
            }

            float shotXs;
            sPos = sData.indexOf(shot,0,Qt::CaseInsensitive);
            cr = sData.mid(sPos,46);
            if(cr.contains("\n"))
            {
                //       cout << " cr " << sPos << endl;
                sPos +=2;
            }

            QString shotX = sData.mid(sPos+46,10);
            //   cout << "shotx " << shotX.toStdString() << endl;
            if(shotX.contains("\n") || shotX.contains("\r"))
            {
                shotX = sData.mid(sPos+46,12);
                int shift1 = shotX.indexOf("\r");
                int shift = shotX.indexOf("\n");
                //           cout << shift1 << " " << shift << endl;
                QString tmp = shotX.mid(0,shift1);
                tmp.append(shotX.mid(shift+1,12));
                shotXs = tmp.toFloat();
            }
            else
            {
                shotXs = shotX.toFloat();
            }
            icount +=sPos+1;
            //     cout << shotNos << endl;
            float shotXt = shotXs - 757551.46;


            float shotYt = shotYs - 978769.0;
            float shotYr = shotYt * cosf(13.661f * M_PI/180.0f) + shotXt * sinf(13.661f * M_PI/180.0f);
            int shotYy = 981 + shotYr/25.0;
            float shotXr = shotXt * cosf(13.661f * M_PI/180.0f) - shotYt * sinf(13.661f * M_PI/180.0f);
            int shotXx = 2570 - shotXr/25.0;
//            if(shotXx>0 && shotYy>0)
//            {
                QPointF shotPoint(shotXx,shotYy);
                curveData.append(shotPoint);
            //    cout << " shot " << shotNos << " " << shotXs  << " " << shotYs << " "  << shotXx << " " << shotYy << endl;
 //           }



        }
        vCurve->setSamples(curveData);
        curves.append(vCurve);
        ukFile->close();
    }
コード例 #25
0
ファイル: AsciiFilter.cpp プロジェクト: luca-penasa/trunk
CC_FILE_ERROR AsciiFilter::saveToFile(ccHObject* entity, QString filename, SaveParameters& parameters)
{
	assert(entity && !filename.isEmpty());

	AsciiSaveDlg* saveDialog = GetSaveDialog(parameters.parentWidget);
	assert(saveDialog);

	//if the dialog shouldn't be shown, we'll simply take the default values!
	if (parameters.alwaysDisplaySaveDialog && saveDialog->autoShow() && !saveDialog->exec())
	{
		return CC_FERR_CANCELED_BY_USER;
	}

	if (!entity->isKindOf(CC_TYPES::POINT_CLOUD))
	{
		if (entity->isA(CC_TYPES::HIERARCHY_OBJECT)) //multiple clouds?
		{
			QFileInfo fi(filename);
			QString extension = fi.suffix();
			QString baseName = fi.completeBaseName();
			QString path = fi.path();

			unsigned count = entity->getChildrenNumber();
			//we count the number of clouds first
			unsigned cloudCount = 0;
			{
				for (unsigned i=0; i<count; ++i)
				{
					ccHObject* child = entity->getChild(i);
					if (child->isKindOf(CC_TYPES::POINT_CLOUD))
						++cloudCount;
				}
			}
			
			//we can now create the corresponding file(s)
			if (cloudCount > 1)
			{
				unsigned counter = 0;
				//disable the save dialog so that it doesn't appear again!
				AsciiSaveDlg* saveDialog = GetSaveDialog();
				assert(saveDialog);

				bool autoShow = saveDialog->autoShow();
				saveDialog->setAutoShow(false);

				for (unsigned i=0; i<count; ++i)
				{
					ccHObject* child = entity->getChild(i);
					if (child->isKindOf(CC_TYPES::POINT_CLOUD))
					{
						QString subFilename = path+QString("/");
						subFilename += QString(baseName).replace("cloudname",child->getName(),Qt::CaseInsensitive);
						counter++;
						assert(counter <= cloudCount);
						subFilename += QString("_%1").arg(cloudCount-counter,6,10,QChar('0'));
						if (!extension.isEmpty())
							subFilename += QString(".") + extension;
						
						CC_FILE_ERROR result = saveToFile(entity->getChild(i),subFilename,parameters);
						if (result != CC_FERR_NO_ERROR)
						{
							return result;
						}
						else
						{
							ccLog::Print(QString("[ASCII] Cloud '%1' has been saved in: %2").arg(child->getName()).arg(subFilename));
						}
					}
					else
					{
						ccLog::Warning(QString("[ASCII] Entity '%1' can't be saved this way!").arg(child->getName()));
					}
				}

				//restore previous state
				saveDialog->setAutoShow(autoShow);

				return CC_FERR_NO_ERROR;
			}
		}
		else
		{
			return CC_FERR_BAD_ARGUMENT;
		}
	}

	QFile file(filename);
	if (!file.open(QFile::WriteOnly | QFile::Truncate))
		return CC_FERR_WRITING;
	QTextStream stream(&file);

	ccGenericPointCloud* cloud = ccHObjectCaster::ToGenericPointCloud(entity);

	unsigned numberOfPoints = cloud->size();
	bool writeColors = cloud->hasColors();
	bool writeNorms = cloud->hasNormals();
	std::vector<ccScalarField*> theScalarFields;
	if (cloud->isKindOf(CC_TYPES::POINT_CLOUD))
	{
		ccPointCloud* ccCloud = static_cast<ccPointCloud*>(cloud);
		for (unsigned i=0; i<ccCloud->getNumberOfScalarFields(); ++i)
			theScalarFields.push_back(static_cast<ccScalarField*>(ccCloud->getScalarField(i)));
	}
	bool writeSF = (theScalarFields.size() != 0);

	//progress dialog
	ccProgressDialog pdlg(true, parameters.parentWidget);
	CCLib::NormalizedProgress nprogress(&pdlg, numberOfPoints);
	if (parameters.parentWidget)
	{
		pdlg.setMethodTitle(QObject::tr("Saving cloud [%1]").arg(cloud->getName()));
		pdlg.setInfo(QObject::tr("Number of points: %1").arg(numberOfPoints));
		pdlg.start();
	}

	//output precision
	const int s_coordPrecision = saveDialog->coordsPrecision();
	const int s_sfPrecision = saveDialog->sfPrecision(); 
	const int s_nPrecision = 2+sizeof(PointCoordinateType);

	//other parameters
	bool saveColumnsHeader = saveDialog->saveColumnsNamesHeader();
	bool savePointCountHeader = saveDialog->savePointCountHeader();
	bool swapColorAndSFs = saveDialog->swapColorAndSF();
	QChar separator(saveDialog->getSeparator());
	bool saveFloatColors = saveDialog->saveFloatColors();

	if (saveColumnsHeader)
	{
		QString header("//");
		header.append(AsciiHeaderColumns::X());
		header.append(separator);
		header.append(AsciiHeaderColumns::Y());
		header.append(separator);
		header.append(AsciiHeaderColumns::Z());

		if (writeColors && !swapColorAndSFs)
		{
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Rf() : AsciiHeaderColumns::R());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Gf() : AsciiHeaderColumns::G());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Bf() : AsciiHeaderColumns::B());
		}

		if (writeSF)
		{
			//add each associated SF name
			for (std::vector<ccScalarField*>::const_iterator it = theScalarFields.begin(); it != theScalarFields.end(); ++it)
			{
				QString sfName((*it)->getName());
				sfName.replace(separator,'_');
				header.append(separator);
				header.append(sfName);
			}
		}

		if (writeColors && swapColorAndSFs)
		{
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Rf() : AsciiHeaderColumns::R());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Gf() : AsciiHeaderColumns::G());
			header.append(separator);
			header.append(saveFloatColors ? AsciiHeaderColumns::Bf() : AsciiHeaderColumns::B());
		}

		if (writeNorms)
		{
			header.append(separator);
			header.append(AsciiHeaderColumns::Nx());
			header.append(separator);
			header.append(AsciiHeaderColumns::Ny());
			header.append(separator);
			header.append(AsciiHeaderColumns::Nz());
		}
		
		stream << header << "\n";
	}

	if (savePointCountHeader)
	{
		stream << QString::number(numberOfPoints) << "\n";
	}

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;
	for (unsigned i=0; i<numberOfPoints; ++i)
	{
		//line for the current point
		QString line;

		//write current point coordinates
		const CCVector3* P = cloud->getPoint(i);
		CCVector3d Pglobal = cloud->toGlobal3d<PointCoordinateType>(*P);
		line.append(QString::number(Pglobal.x,'f',s_coordPrecision));
		line.append(separator);
		line.append(QString::number(Pglobal.y,'f',s_coordPrecision));
		line.append(separator);
		line.append(QString::number(Pglobal.z,'f',s_coordPrecision));

		QString colorLine;
		if (writeColors)
		{
			//add rgb color
			const ColorCompType* col = cloud->getPointColor(i);
			if (saveFloatColors)
			{
				colorLine.append(separator);
				colorLine.append(QString::number(static_cast<double>(col[0])/ccColor::MAX));
				colorLine.append(separator);
				colorLine.append(QString::number(static_cast<double>(col[1])/ccColor::MAX));
				colorLine.append(separator);
				colorLine.append(QString::number(static_cast<double>(col[2])/ccColor::MAX));
			}
			else
			{
				colorLine.append(separator);
				colorLine.append(QString::number(col[0]));
				colorLine.append(separator);
				colorLine.append(QString::number(col[1]));
				colorLine.append(separator);
				colorLine.append(QString::number(col[2]));
			}

			if (!swapColorAndSFs)
				line.append(colorLine);
		}

		if (writeSF)
		{
			//add each associated SF values
			for (std::vector<ccScalarField*>::const_iterator it = theScalarFields.begin(); it != theScalarFields.end(); ++it)
			{
				line.append(separator);
				double sfVal = (*it)->getGlobalShift() + (*it)->getValue(i);
				line.append(QString::number(sfVal,'f',s_sfPrecision));
			}
		}

		if (writeColors && swapColorAndSFs)
			line.append(colorLine);

		if (writeNorms)
		{
			//add normal vector
			const CCVector3& N = cloud->getPointNormal(i);
			line.append(separator);
			line.append(QString::number(N.x,'f',s_nPrecision));
			line.append(separator);
			line.append(QString::number(N.y,'f',s_nPrecision));
			line.append(separator);
			line.append(QString::number(N.z,'f',s_nPrecision));
		}

		stream << line << "\n";

		if (parameters.parentWidget && !nprogress.oneStep())
		{
			result = CC_FERR_CANCELED_BY_USER;
			break;
		}
	}

	return result;
}
コード例 #26
0
ファイル: kjoapi.cpp プロジェクト: retifrav/scratches
void KjoMsgDbLayer::preparations4select(KjoMsgFilter *recFilter)
{
    if(!recFilter->isSelectAllToDo())
    {
        _listOfConditions->append(recFilter);
        // временная строка для одного блока WHERE
        QString tempWhere;

        QVariant typ = recFilter->get_msg_type_record(),
                 sts = recFilter->get_msg_status_record(),
                 dtf = recFilter->get_msg_datetimeFrom(),
                 dtt = recFilter->get_msg_datetimeTo(),
                 msg = recFilter->get_msg_record(),
                 cod = recFilter->get_msg_code_record(),
                 sdr = recFilter->get_msg_sender_record(),
//                 usr = recFilter->get_msg_user_record(),
                 ipa = recFilter->get_user_ip_record();

        tempWhere.append("(");

        if(typ != NULL)
            tempWhere.append("msg_type_record = cast("
                        + typ.toString()
                        + " as smallint) AND ");
        if(sts != NULL)
            tempWhere.append("msg_status_record = cast("
                        + sts.toString()
                        + " as smallint) AND ");
        if(dtf != NULL && dtt != NULL)
            tempWhere.append("msg_date_record BETWEEN cast('"
                        + dtf.toString()
                        + "' as timestamp without time zone) "
                         "AND cast('"
                        + dtt.toString()
                        + "' as timestamp without time zone) AND ");
        if(msg != QString())
            tempWhere.append("msg_record LIKE '%"
                        + msg.toString() + "%' AND ");
        if(cod != QString())
            tempWhere.append("msg_code_record = '"
                        + cod.toString() + "' AND ");
        if(sdr != QString())
            tempWhere.append("msg_sender_record = '"
                        + sdr.toString() + "' AND ");
//        if(usr != QString())
//            tempWhere.append("msg_user_record = '"
//                        + usr.toString() + "' AND ");
        if(ipa != QString())
            tempWhere.append("user_ip_record = '"
                        + ipa.toString() + "' AND ");

        // удалить из строки пробел, AND, ещё пробел, поставить скобку и OR
        tempWhere.chop(5); tempWhere.append(") OR ");

        _where4select.append(tempWhere);

        QStandardItem *oneMoreOr = new QStandardItem(tempWhere);
        _model4queryDetailed->appendRow(oneMoreOr);
//        qDebug() << _model4queryDetailed->item(_model4queryDetailed->rowCount() - 1)->text();
//        for(int x = 0; x < _listOfConditions->count(); x++)
//            qDebug() << _listOfConditions->at(x)->get_msg_record();
    }
}
コード例 #27
0
ファイル: MainWindow.cpp プロジェクト: Krabi/idkaart_public
bool MainWindow::addFile( const QString &file )
{
	QFileInfo fileinfo( file );
	if( doc->isNull() )
	{
		Settings s;
		s.beginGroup( "Crypto" );
		QString docname = QString( "%1/%2.cdoc" )
			.arg( s.value( "DefaultDir", fileinfo.absolutePath() ).toString() )
			.arg( fileinfo.fileName() );

		bool select = s.value( "AskSaveAs", false ).toBool();
		if( !select && QFile::exists( docname ) )
		{
			QMessageBox::StandardButton b = QMessageBox::warning( this, tr("DigiDoc3 crypto"),
				tr( "%1 already exists.<br />Do you want replace it?" ).arg( docname ),
				QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
			select = b == QMessageBox::No;
		}

		if( !Common::canWrite( docname ) )
		{
			select = true;
			qApp->showWarning( tr("You dont have permissions to write file %1").arg( docname ) );
		}

		while( select )
		{
			docname = Common::normalized( QFileDialog::getSaveFileName(
				this, tr("Save file"), docname, tr("Documents (*.cdoc)") ) );
			if( docname.isEmpty() )
				return false;
			if( QFileInfo( docname ).suffix().toLower() != "cdoc" )
				docname.append( ".cdoc" );
			if( !Common::canWrite( docname ) )
				qApp->showWarning( tr("You dont have permissions to write file %1").arg( docname ) );
			else
				select = false;
		}

		if( QFile::exists( docname ) )
			QFile::remove( docname );
		doc->create( docname );
	}

	if( !fileinfo.exists() )
	{
		qApp->showWarning( tr("File does not exists %1").arg( fileinfo.absoluteFilePath() ) );
		return false;
	}

	// Check if file exist and ask confirmation to overwrite
	QList<CDocument> docs = doc->documents();
	for( int i = 0; i < docs.size(); ++i )
	{
		if( QFileInfo( docs[i].filename ).fileName() == fileinfo.fileName() )
		{
			QMessageBox::StandardButton btn = QMessageBox::warning( this,
				tr("File already in container"),
				tr("%1<br />already in container, ovewrite?").arg( fileinfo.fileName() ),
				QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
			if( btn == QMessageBox::Yes )
			{
				doc->removeDocument( i );
				break;
			}
			else
				return true;
		}
	}

	doc->addFile( file, "" );
	return true;
}
コード例 #28
0
ファイル: packagejobthread.cpp プロジェクト: KDE/kpackage
bool PackageJobThread::installPackage(const QString &src, const QString &dest, OperationType operation)
{
    QDir root(dest);
    if (!root.exists()) {
        QDir().mkpath(dest);
        if (!root.exists()) {
            d->errorMessage = i18n("Could not create package root directory: %1", dest);
            d->errorCode = Package::JobError::RootCreationError;
            //qWarning() << "Could not create package root directory: " << dest;
            return false;
        }
    }

    QFileInfo fileInfo(src);
    if (!fileInfo.exists()) {
        d->errorMessage = i18n("No such file: %1", src);
        d->errorCode = Package::JobError::PackageFileNotFoundError;
        return false;
    }

    QString path;
    QTemporaryDir tempdir;
    bool archivedPackage = false;

    if (fileInfo.isDir()) {
        // we have a directory, so let's just install what is in there
        path = src;
        // make sure we end in a slash!
        if (!path.endsWith('/')) {
            path.append('/');
        }
    } else {
        KArchive *archive = 0;
        QMimeDatabase db;
        QMimeType mimetype = db.mimeTypeForFile(src);
        if (mimetype.inherits(QStringLiteral("application/zip"))) {
            archive = new KZip(src);
        } else if (mimetype.inherits(QStringLiteral("application/x-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-bzip-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-xz")) ||
                   mimetype.inherits(QStringLiteral("application/x-lzma"))) {
            archive = new KTar(src);
        } else {
            //qWarning() << "Could not open package file, unsupported archive format:" << src << mimetype.name();
            d->errorMessage = i18n("Could not open package file, unsupported archive format: %1 %2", src, mimetype.name());
            d->errorCode = Package::JobError::UnsupportedArchiveFormatError;
            return false;
        }

        if (!archive->open(QIODevice::ReadOnly)) {
            //qWarning() << "Could not open package file:" << src;
            delete archive;
            d->errorMessage = i18n("Could not open package file: %1", src);
            d->errorCode = Package::JobError::PackageOpenError;
            return false;
        }

        archivedPackage = true;
        path = tempdir.path() + '/';

        d->installPath = path;

        const KArchiveDirectory *source = archive->directory();
        source->copyTo(path);

        QStringList entries = source->entries();
        if (entries.count() == 1) {
            const KArchiveEntry *entry = source->entry(entries[0]);
            if (entry->isDirectory()) {
                path.append(entry->name()).append("/");
            }
        }

        delete archive;
    }

    QDir packageDir(path);
    QFileInfoList entries = packageDir.entryInfoList(*metaDataFiles);
    KPluginMetaData meta;
    if (!entries.isEmpty()) {
        const QString metadataFilePath = entries.first().filePath();
        if (metadataFilePath.endsWith(QLatin1String(".desktop")))
            meta = KPluginMetaData(metadataFilePath);
        else {
            QFile f(metadataFilePath);
            if(!f.open(QIODevice::ReadOnly)){
                qWarning() << "Couldn't open metadata file" << src << path;
                d->errorMessage = i18n("Could not open metadata file: %1", src);
                d->errorCode = Package::JobError::MetadataFileMissingError;
                return false;
            }
            QJsonObject metadataObject = QJsonDocument::fromJson(f.readAll()).object();
            meta = KPluginMetaData(metadataObject, QString(), metadataFilePath);
        }
    }

    if (!meta.isValid()) {
        qDebug() << "No metadata file in package" << src << path;
        d->errorMessage = i18n("No metadata file in package: %1", src);
        d->errorCode = Package::JobError::MetadataFileMissingError;
        return false;
    }


    QString pluginName = meta.pluginId();
    qDebug() << "pluginname: " << meta.pluginId();
    if (pluginName.isEmpty()) {
        //qWarning() << "Package plugin name not specified";
        d->errorMessage = i18n("Package plugin name not specified: %1", src);
        d->errorCode = Package::JobError::PluginNameMissingError;
        return false;
    }

    // Ensure that package names are safe so package uninstall can't inject
    // bad characters into the paths used for removal.
    QRegExp validatePluginName("^[\\w-\\.]+$"); // Only allow letters, numbers, underscore and period.
    if (!validatePluginName.exactMatch(pluginName)) {
        //qDebug() << "Package plugin name " << pluginName << "contains invalid characters";
        d->errorMessage = i18n("Package plugin name %1 contains invalid characters", pluginName);
        d->errorCode = Package::JobError::PluginNameInvalidError;
        return false;
    }

    QString targetName = dest;
    if (targetName[targetName.size() - 1] != '/') {
        targetName.append('/');
    }
    targetName.append(pluginName);

    if (QFile::exists(targetName)) {
        if (operation == Update) {
            KPluginMetaData oldMeta(targetName + QLatin1String("/metadata.desktop"));

            if (oldMeta.serviceTypes() != meta.serviceTypes()) {
                d->errorMessage = i18n("The new package has a different type from the old version already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::UpdatePackageTypeMismatchError;
            } else if (isVersionNewer(oldMeta.version(), meta.version())) {
                const bool ok = uninstallPackage(targetName);
                if (!ok) {
                    d->errorMessage = i18n("Impossible to remove the old installation of %1 located at %2. error: %3", pluginName, targetName, d->errorMessage);
                    d->errorCode = Package::JobError::OldVersionRemovalError;
                }
            } else {
                d->errorMessage = i18n("Not installing version %1 of %2. Version %3 already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::NewerVersionAlreadyInstalledError;
            }
        } else {
            d->errorMessage = i18n("%1 already exists", targetName);
            d->errorCode = Package::JobError::PackageAlreadyInstalledError;
        }

        if (d->errorCode != KJob::NoError) {
            d->installPath = targetName;
            return false;
        }
    }

    //install dependencies
    const QStringList dependencies = KPluginMetaData::readStringList(meta.rawData(), QStringLiteral("X-KPackage-Dependencies"));
    for(const QString &dep : dependencies) {
        QUrl depUrl(dep);
        if (!installDependency(depUrl)) {
            d->errorMessage = i18n("Could not install dependency: %1", dep);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // it's in a temp dir, so just move it over.
        const bool ok = copyFolder(path, targetName);
        removeFolder(path);
        if (!ok) {
            //qWarning() << "Could not move package to destination:" << targetName;
            d->errorMessage = i18n("Could not move package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageMoveError;
            return false;
        }
    } else {
        // it's a directory containing the stuff, so copy the contents rather
        // than move them
        const bool ok = copyFolder(path, targetName);
        if (!ok) {
            //qWarning() << "Could not copy package to destination:" << targetName;
            d->errorMessage = i18n("Could not copy package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // no need to remove the temp dir (which has been successfully moved if it's an archive)
        tempdir.setAutoRemove(false);
    }


    indexDirectory(dest, QStringLiteral("kpluginindex.json"));


    d->installPath = targetName;

    //qWarning() << "Not updating kbuildsycoca4, since that will go away. Do it yourself for now if needed.";
    return true;
}
コード例 #29
0
bool QgsAttributeEditor::retrieveValue( QWidget *widget, QgsVectorLayer *vl, int idx, QVariant &value )
{
  if ( !widget )
    return false;

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

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

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

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

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

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

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

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

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

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

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

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

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

  le = widget->findChild<QLineEdit *>();
  // QCalendarWidget and QGroupBox have an internal QLineEdit which returns the year
  // part of the date so we need to skip this if we have a QCalendarWidget
  if ( !cw && !gb && le )
  {
    text = le->text();
  }

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

  return modified;
}
コード例 #30
0
void MainWindow::adjustSettings()
{
    QAudioFormat inputFormat = m_audio_lib->inputAudioFormat();
    QAudioFormat format = m_audio_lib->audioFormat();

    QString str;

    str.append("Input format:\n\n");

    str.append(QString("Sample size: %0 bits\n").arg(inputFormat.sampleSize()));
    str.append(QString("Sample rate: %0 hz\n").arg(inputFormat.sampleRate()));
    str.append(QString("Channels: %0\n").arg(inputFormat.channelCount()));
    str.append(QString("Sample type: %0\n").arg((inputFormat.sampleType()  == QAudioFormat::Float) ? "Float" : "Integer"));
    str.append(QString("Byte order: %0\n").arg((inputFormat.byteOrder() == QAudioFormat::LittleEndian) ? "Little endian" : "Big endian"));

    str.append("\n");

    str.append("Resampled format:\n\n");

    str.append(QString("Sample size: %0 bits\n").arg(format.sampleSize()));
    str.append(QString("Sample rate: %0 hz\n").arg(format.sampleRate()));
    str.append(QString("Channels: %0\n").arg(format.channelCount()));
    str.append(QString("Sample type: %0\n").arg((format.sampleType()  == QAudioFormat::Float) ? "Float" : "Integer"));
    str.append(QString("Byte order: %0").arg((format.byteOrder() == QAudioFormat::LittleEndian) ? "Little endian" : "Big endian"));

    str.append("\n\n");

    str.append("Eigen instructions set:\n");

    str.append(AudioStreamingLibCore::EigenInstructionsSet());

    texteditsettings->setPlainText(str);

    if (!m_spectrum_analyzer)
    {
        m_spectrum_analyzer = new SpectrumAnalyzer();
        QThread *thread = new QThread();
        m_spectrum_analyzer->moveToThread(thread);

        connect(m_audio_lib, &AudioStreamingLibCore::veryInputData, m_spectrum_analyzer, &SpectrumAnalyzer::calculateSpectrum);
        connect(m_spectrum_analyzer, &SpectrumAnalyzer::spectrumChanged, bars, &BarsWidget::setValues);
        connect(m_spectrum_analyzer, &SpectrumAnalyzer::destroyed, bars, &BarsWidget::clear);

        connect(m_audio_lib, &AudioStreamingLibCore::finished, m_spectrum_analyzer, &SpectrumAnalyzer::deleteLater);
        connect(this, &MainWindow::destroyed, m_spectrum_analyzer, &SpectrumAnalyzer::deleteLater);
        connect(m_spectrum_analyzer, &SpectrumAnalyzer::destroyed, thread, &QThread::quit);
        connect(thread, &QThread::finished, thread, &QThread::deleteLater);

        QMetaObject::invokeMethod(m_spectrum_analyzer, "start", Qt::QueuedConnection, Q_ARG(QAudioFormat, format));

        thread->start();
    }

    {
        waveform->start(format);
        connect(m_audio_lib, &AudioStreamingLibCore::veryInputData, waveform, &WaveFormWidget::calculateWaveForm);
        connect(m_audio_lib, &AudioStreamingLibCore::finished, waveform, &WaveFormWidget::clear);
    }

    {
        connect(m_audio_lib, &AudioStreamingLibCore::veryInputData, level, &LevelWidget::calculateRMSLevel);
    }
}