本文整理汇总了C++中QString::at方法的典型用法代码示例。如果您正苦于以下问题:C++ QString::at方法的具体用法?C++ QString::at怎么用?C++ QString::at使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QString
的用法示例。
在下文中一共展示了QString::at方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: validateAndInterpret
Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const
{
Base::Quantity res;
const double max = this->maximum;
const double min = this->minimum;
QString copy = input;
int len = copy.size();
const bool plus = max >= 0;
const bool minus = min <= 0;
switch (len) {
case 0:
state = max != min ? QValidator::Intermediate : QValidator::Invalid;
goto end;
case 1:
if (copy.at(0) == locale.decimalPoint()) {
state = QValidator::Intermediate;
copy.prepend(QLatin1Char('0'));
pos++;
len++;
goto end;
}
else if (copy.at(0) == QLatin1Char('+')) {
// the quantity parser doesn't allow numbers of the form '+1.0'
state = QValidator::Invalid;
goto end;
}
else if (copy.at(0) == QLatin1Char('-')) {
if (minus)
state = QValidator::Intermediate;
else
state = QValidator::Invalid;
goto end;
}
break;
case 2:
if (copy.at(1) == locale.decimalPoint()
&& (plus && copy.at(0) == QLatin1Char('+'))) {
state = QValidator::Intermediate;
goto end;
}
if (copy.at(1) == locale.decimalPoint()
&& (minus && copy.at(0) == QLatin1Char('-'))) {
state = QValidator::Intermediate;
copy.insert(1, QLatin1Char('0'));
pos++;
len++;
goto end;
}
break;
default: break;
}
{
if (copy.at(0) == locale.groupSeparator()) {
state = QValidator::Invalid;
goto end;
}
else if (len > 1) {
bool decOccurred = false;
for (int i = 0; i<copy.size(); i++) {
if (copy.at(i) == locale.decimalPoint()) {
// Disallow multiple decimal points within the same numeric substring
if (decOccurred) {
state = QValidator::Invalid;
goto end;
}
decOccurred = true;
}
// Reset decOcurred if non-numeric character found
else if (!(copy.at(i) == locale.groupSeparator() || copy.at(i).isDigit())) {
decOccurred = false;
}
}
}
bool ok = false;
double value = min;
if (locale.negativeSign() != QLatin1Char('-'))
copy.replace(locale.negativeSign(), QLatin1Char('-'));
if (locale.positiveSign() != QLatin1Char('+'))
copy.replace(locale.positiveSign(), QLatin1Char('+'));
try {
QString copy2 = copy;
copy2.remove(locale.groupSeparator());
res = Base::Quantity::parse(copy2);
value = res.getValue();
ok = true;
}
catch (Base::Exception&) {
}
if (!ok) {
// input may not be finished
//.........这里部分代码省略.........
示例2: load
/*!
Load, parse, and process a qdoc configuration file. This
function is only called by the other load() function, but
this one is recursive, i.e., it calls itself when it sees
an \c{include} statement in the qdog configuration file.
*/
void Config::load(Location location, const QString& fileName)
{
QRegExp keySyntax("\\w+(?:\\.\\w+)*");
#define SKIP_CHAR() \
do { \
location.advance(c); \
++i; \
c = text.at(i); \
cc = c.unicode(); \
} while (0)
#define SKIP_SPACES() \
while (c.isSpace() && cc != '\n') \
SKIP_CHAR()
#define PUT_CHAR() \
word += c; \
SKIP_CHAR();
if (location.depth() > 16)
location.fatal(tr("Too many nested includes"));
QFile fin(fileName);
if (!fin.open(QFile::ReadOnly | QFile::Text)) {
fin.setFileName(fileName + ".qdoc");
if (!fin.open(QFile::ReadOnly | QFile::Text))
location.fatal(tr("Cannot open file '%1': %2").arg(fileName).arg(fin.errorString()));
}
QTextStream stream(&fin);
stream.setCodec("UTF-8");
QString text = stream.readAll();
text += QLatin1String("\n\n");
text += QChar('\0');
fin.close();
location.push(fileName);
location.start();
int i = 0;
QChar c = text.at(0);
uint cc = c.unicode();
while (i < (int) text.length()) {
if (cc == 0)
++i;
else if (c.isSpace()) {
SKIP_CHAR();
}
else if (cc == '#') {
do {
SKIP_CHAR();
} while (cc != '\n');
}
else if (isMetaKeyChar(c)) {
Location keyLoc = location;
bool plus = false;
QString stringValue;
QStringList stringListValue;
QString word;
bool inQuote = false;
bool prevWordQuoted = true;
bool metWord = false;
MetaStack stack;
do {
stack.process(c, location);
SKIP_CHAR();
} while (isMetaKeyChar(c));
QStringList keys = stack.getExpanded(location);
//qDebug() << "KEYS:" << keys;
SKIP_SPACES();
if (keys.count() == 1 && keys.first() == "include") {
QString includeFile;
if (cc != '(')
location.fatal(tr("Bad include syntax"));
SKIP_CHAR();
SKIP_SPACES();
while (!c.isSpace() && cc != '#' && cc != ')') {
includeFile += c;
SKIP_CHAR();
}
SKIP_SPACES();
if (cc != ')')
location.fatal(tr("Bad include syntax"));
SKIP_CHAR();
SKIP_SPACES();
if (cc != '#' && cc != '\n')
location.fatal(tr("Trailing garbage"));
/*
//.........这里部分代码省略.........
示例3: getItem
void DrugStorage::getItem(int row,int column)//计算费用
{
QString str2;
QString str = str.fromLocal8Bit("警告");
if (column==6)
{
if (ui.tableWidget->item(row,column)->text()==NULL) return;
if (ui.tableWidget->item(row,column+2)->text()==NULL) return;
int icount = ui.tableWidget->item(row,column)->text().toInt();
if(icount<0)
{
str2 = str.fromLocal8Bit("收货数量不能为负,请核对!");
QMessageBox::warning(this,str,str2,QMessageBox::Ok);
QString stramount = QString::number(0);
ui.tableWidget->setItem(row,column,new QTableWidgetItem(stramount));
return;
}
double unitprice = ui.tableWidget->item(row,column+2)->text().toDouble();
double amount = icount*unitprice;
QString stramount = QString::number(amount);
ui.tableWidget->setItem(row,column+3,new QTableWidgetItem(stramount));
double icurrentamount = TotalPrice();
QString strcurrentamount = QString::number(icurrentamount);
//累加
ui.lineEdit_Payable->setText(strcurrentamount);
double iamount = ui.lineEdit_Paid->text().toInt();
iamount = iamount - icurrentamount;
/*if(ui.radioButton_Add->isChecked() && !ui.radioButton_Minus->isChecked())
iamount = iamount - icurrentamount;
if(!ui.radioButton_Add->isChecked() && ui.radioButton_Minus->isChecked())
iamount = iamount + icurrentamount;*/
strcurrentamount = QString::number(iamount);
ui.lineEdit_debt->setText(strcurrentamount);
}
if(column==0)
{
list_widget->close();
QString strText;
if(ui.tableWidget->item(row,0)==NULL) return;
strText = ui.tableWidget->item(row,0)->text();
if(strText.at(0)== QChar('1')) return;
list_widget->setGeometry(103, 160+row*30, 150, 280);
list_widget->show();
QSqlQuery query(*sql.db);
strText = ui.tableWidget->item(row,0)->text();
QString strsql= QString("select * from sys_drugdictionary where abbr like '%%1%'or name like'%%2%' ").arg(strText).arg(strText);
query.exec(strsql);
QStringList list;
list_widget->clear();
while(query.next())
{
QString str = query.value(1).toString();
list.append(str);
}
list_widget->addItems(list);
}
}
示例4: formatValue
/*!
Returns a string representation of the \a field value for the
database. This is used, for example, when constructing INSERT and
UPDATE statements.
The default implementation returns the value formatted as a string
according to the following rules:
\list
\li If \a field is character data, the value is returned enclosed
in single quotation marks, which is appropriate for many SQL
databases. Any embedded single-quote characters are escaped
(replaced with two single-quote characters). If \a trimStrings is
true (the default is false), all trailing whitespace is trimmed
from the field.
\li If \a field is date/time data, the value is formatted in ISO
format and enclosed in single quotation marks. If the date/time
data is invalid, "NULL" is returned.
\li If \a field is \l{QByteArray}{bytearray} data, and the
driver can edit binary fields, the value is formatted as a
hexadecimal string.
\li For any other field type, toString() is called on its value
and the result of this is returned.
\endlist
\sa QVariant::toString()
*/
QString QSqlDriver::formatValue(const QSqlField &field, bool trimStrings) const
{
const QLatin1String nullTxt("NULL");
QString r;
if (field.isNull())
r = nullTxt;
else {
switch (field.type()) {
case QVariant::Int:
case QVariant::UInt:
if (field.value().type() == QVariant::Bool)
r = field.value().toBool() ? QLatin1String("1") : QLatin1String("0");
else
r = field.value().toString();
break;
#ifndef QT_NO_DATESTRING
case QVariant::Date:
if (field.value().toDate().isValid())
r = QLatin1Char('\'') + field.value().toDate().toString(Qt::ISODate)
+ QLatin1Char('\'');
else
r = nullTxt;
break;
case QVariant::Time:
if (field.value().toTime().isValid())
r = QLatin1Char('\'') + field.value().toTime().toString(Qt::ISODate)
+ QLatin1Char('\'');
else
r = nullTxt;
break;
case QVariant::DateTime:
if (field.value().toDateTime().isValid())
r = QLatin1Char('\'') +
field.value().toDateTime().toString(Qt::ISODate) + QLatin1Char('\'');
else
r = nullTxt;
break;
#endif
case QVariant::String:
case QVariant::Char:
{
QString result = field.value().toString();
if (trimStrings) {
int end = result.length();
while (end && result.at(end-1).isSpace()) /* skip white space from end */
end--;
result.truncate(end);
}
/* escape the "'" character */
result.replace(QLatin1Char('\''), QLatin1String("''"));
r = QLatin1Char('\'') + result + QLatin1Char('\'');
break;
}
case QVariant::Bool:
r = QString::number(field.value().toBool());
break;
case QVariant::ByteArray : {
if (hasFeature(BLOB)) {
QByteArray ba = field.value().toByteArray();
QString res;
static const char hexchars[] = "0123456789abcdef";
for (int i = 0; i < ba.size(); ++i) {
uchar s = (uchar) ba[i];
res += QLatin1Char(hexchars[s >> 4]);
res += QLatin1Char(hexchars[s & 0x0f]);
}
//.........这里部分代码省略.........
示例5: readLevelMolecule
const Molecule* LevelSet::readLevelMolecule(int levelNum) const
{
Molecule* mol = new Molecule();
KConfigGroup config = m_levelsFile->group("Level"+QString::number(levelNum));
QString key;
atom current;
int atom_index = 1;
QString value;
while (true) {
key.sprintf("atom_%c", int2atom(atom_index));
value = config.readEntry(key,QString());
if (value.isEmpty())
break;
current.obj = value.at(0).toLatin1();
value = value.mid(2);
strncpy(current.conn, value.toLatin1(), sizeof(current.conn));
if (mol->m_atoms.indexOf(current) != -1)
qWarning()
<< "OOOPS, duplicate atom definition in" << key;
mol->m_atoms.append(current);
atom_index++;
}
QString line;
mol->m_width = 0;
mol->m_height = 0;
mol->m_weight = 0.0;
int max_i = -1;
for (int j = 0; j < MOLECULE_SIZE; j++) {
key.sprintf("mole_%d", j);
line = config.readEntry(key,QString());
int max_non_null_i = -1;
for (int i = 0; i < MOLECULE_SIZE; i++)
{
if (i >= line.size())
mol->m_molek[i][j] = 0;
else
{
mol->m_molek[i][j] = atom2int(line.at(i).toLatin1());
mol->m_weight += mol->getAtom(mol->m_molek[i][j]).weight();
max_non_null_i = i;
}
}
if( max_non_null_i != -1 )
mol->m_height++;
max_i = qMax( max_i, max_non_null_i );
}
mol->m_width = max_i+1;
mol->m_name = i18n(config.readEntry("Name", I18N_NOOP("Noname")).toUtf8());
return mol;
}
示例6: removeDelimiters
void HighlightDefinition::removeDelimiters(const QString &characters)
{
for (int i = 0; i < characters.length(); ++i)
m_delimiters.remove(characters.at(i));
}
示例7: readProcessOutput
void MiningPage::readProcessOutput()
{
QByteArray output;
minerProcess->reset();
output = minerProcess->readAll();
QString outputString(output);
if (!outputString.isEmpty())
{
QStringList list = outputString.split("\n", QString::SkipEmptyParts);
int i;
for (i=0; i<list.size(); i++)
{
QString line = list.at(i);
// Ignore protocol dump
if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
continue;
if (ui->debugCheckBox->isChecked())
{
ui->list->addItem(line.trimmed());
ui->list->scrollToBottom();
}
if (line.contains("(yay!!!)"))
reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
else if (line.contains("(booooo)"))
reportToList("Share rejected", SHARE_FAIL, getTime(line));
else if (line.contains("LONGPOLL detected new block"))
reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
else if (line.contains("Supported options:"))
reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
else if (line.contains("The requested URL returned error: 403"))
reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
else if (line.contains("HTTP request failed"))
reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
else if (line.contains("JSON-RPC call failed"))
reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
else if (line.contains("thread ") && line.contains("khash/s"))
{
QString threadIDstr = line.at(line.indexOf("thread ")+7);
int threadID = threadIDstr.toInt();
int threadSpeedindx = line.indexOf(",");
QString threadSpeedstr = line.mid(threadSpeedindx);
threadSpeedstr.chop(8);
threadSpeedstr.remove(", ");
threadSpeedstr.remove(" ");
threadSpeedstr.remove('\n');
double speed=0;
speed = threadSpeedstr.toDouble();
threadSpeed[threadID] = speed;
updateSpeed();
}
}
}
}
示例8: fillMetaData
//static
bool QFileSystemEngine::fillMetaData(const QFileSystemEntry &entry, QFileSystemMetaData &data,
QFileSystemMetaData::MetaDataFlags what)
{
#if defined(Q_OS_DARWIN)
if (what & QFileSystemMetaData::BundleType) {
if (!data.hasFlags(QFileSystemMetaData::DirectoryType))
what |= QFileSystemMetaData::DirectoryType;
}
if (what & QFileSystemMetaData::HiddenAttribute) {
// OS X >= 10.5: st_flags & UF_HIDDEN
what |= QFileSystemMetaData::PosixStatFlags;
}
#endif // defined(Q_OS_DARWIN)
if (what & QFileSystemMetaData::PosixStatFlags)
what |= QFileSystemMetaData::PosixStatFlags;
if (what & QFileSystemMetaData::ExistsAttribute) {
// FIXME: Would other queries being performed provide this bit?
what |= QFileSystemMetaData::PosixStatFlags;
}
data.entryFlags &= ~what;
const char * nativeFilePath;
int nativeFilePathLength;
{
const QByteArray &path = entry.nativeFilePath();
nativeFilePath = path.constData();
nativeFilePathLength = path.size();
Q_UNUSED(nativeFilePathLength);
}
bool entryExists = true; // innocent until proven otherwise
QT_STATBUF statBuffer;
bool statBufferValid = false;
if (what & QFileSystemMetaData::LinkType) {
if (QT_LSTAT(nativeFilePath, &statBuffer) == 0) {
if (S_ISLNK(statBuffer.st_mode)) {
data.entryFlags |= QFileSystemMetaData::LinkType;
} else {
statBufferValid = true;
data.entryFlags &= ~QFileSystemMetaData::PosixStatFlags;
}
} else {
entryExists = false;
}
data.knownFlagsMask |= QFileSystemMetaData::LinkType;
}
if (statBufferValid || (what & QFileSystemMetaData::PosixStatFlags)) {
if (entryExists && !statBufferValid)
statBufferValid = (QT_STAT(nativeFilePath, &statBuffer) == 0);
if (statBufferValid)
data.fillFromStatBuf(statBuffer);
else {
entryExists = false;
data.creationTime_ = 0;
data.modificationTime_ = 0;
data.accessTime_ = 0;
data.size_ = 0;
data.userId_ = (uint) -2;
data.groupId_ = (uint) -2;
}
// reset the mask
data.knownFlagsMask |= QFileSystemMetaData::PosixStatFlags
| QFileSystemMetaData::ExistsAttribute;
}
#if defined(Q_OS_DARWIN)
if (what & QFileSystemMetaData::AliasType)
{
if (entryExists && hasResourcePropertyFlag(data, entry, kCFURLIsAliasFileKey))
data.entryFlags |= QFileSystemMetaData::AliasType;
data.knownFlagsMask |= QFileSystemMetaData::AliasType;
}
#endif
if (what & QFileSystemMetaData::UserPermissions) {
// calculate user permissions
if (entryExists) {
if (what & QFileSystemMetaData::UserReadPermission) {
if (QT_ACCESS(nativeFilePath, R_OK) == 0)
data.entryFlags |= QFileSystemMetaData::UserReadPermission;
}
if (what & QFileSystemMetaData::UserWritePermission) {
if (QT_ACCESS(nativeFilePath, W_OK) == 0)
data.entryFlags |= QFileSystemMetaData::UserWritePermission;
}
if (what & QFileSystemMetaData::UserExecutePermission) {
if (QT_ACCESS(nativeFilePath, X_OK) == 0)
data.entryFlags |= QFileSystemMetaData::UserExecutePermission;
}
}
//.........这里部分代码省略.........
示例9:
/*!
*\~english
* Converted currency value to string representation (ru currency).
*\~russian
* Конвертирует валюту, записанную в виде рублей и копеек в ее текстовое представление.
*\~
* \return - \~english Converted value \~russian Сконвертированное значение \~
* \see number2money(double rubli)
* \see part2string(unsigned int st3, unsigned int st2, unsigned int st1, int stepen)
*/
QString
aService::parts2money(Q_ULLONG rubli,
unsigned int kopeyki,
bool need_kopeyki,
bool positive,
bool male,
const QString &end1,
const QString &end2,
const QString &end3)
{
// if(cur!=ru) return QString("%1 dollars %2 cents").arg(rubli).arg(kopeyki);
QString chislo = (QString("%1").arg(rubli));
int len = chislo.length();
//printf("length=%d\n",len);
int count=0;
int a,b,c;
int stepen=(len-1)/3;
int offset=(len%3);
if(offset) offset = 3-offset;
//printf("offset=%d\n",offset);
QString res = "";
bool has_sum=false;
if(!positive) res+="минус ";
while(count<len)
{
a=b=c=0;
if(offset<=0)
{
a = chislo.at(count++).digitValue();
}
if(count<len)
{
if(offset<=1)
{
b = chislo.at(count++).digitValue();
}
}
if(count<len)
{
if(offset<=2)
{
c = chislo.at(count++).digitValue();
}
}
// printf("a=%d, b=%d, c=%d, stepen=%d\n",a,b,c,stepen);
if(a==0 && b==0 && c==0)
{
if(stepen==0 && has_sum)
{
res+=part2string(a,b,c,stepen--,male,end1,end2,end3);
}
else
{
if(stepen==0)
{
res+=QString("ноль %1").arg(end1);
}
else
{
stepen--;
}
}
}
else
{
has_sum=true;
res+=part2string(a,b,c,stepen--,male,end1,end2,end3);
}
offset=0;
}
if(need_kopeyki)
{
res+=part2string(0,kopeyki/10,kopeyki%10,-1,false,"копеек","копейка","копейки");
}
res = res.stripWhiteSpace();
res = res.replace(0,1,res.at(0).upper());
return res;
}
示例10: keyPressEvent
bool WorksheetPrivate::keyPressEvent(QKeyEvent *ev)
{
ensure_caret(ws);
if (ev == QKeySequence::SelectAll)
return false;
if ((ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) &&
ev->modifiers() == Qt::ControlModifier)
{
if (ev->key() == Qt::Key_Up)
historyPrev();
else
historyNext();
ev->accept();
return true;
}
if ((ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) &&
ev->modifiers() == Qt::AltModifier)
{
QTextCursor cr = ws->textCursor();
if (ev->key() == Qt::Key_Up)
prev_block(cr);
else
next_block(cr);
ws->setTextCursor(cr);
ws->ensureCursorVisible();
ev->accept();
return true;
}
bool handled;
if (cursorMoveKeyEvent(ev, handled))
{
if (handled)
{
ev->accept();
ws->ensureCursorVisible();
}
return handled;
}
if (ev == QKeySequence::Copy)
{
ws->copy();
ev->accept();
return true;
}
if (ev == QKeySequence::Cut)
{
ws->cut();
goto done;
}
if (ev == QKeySequence::Paste)
{
ws->paste();
goto done;
}
if (ev == QKeySequence::Undo)
{
ws->undo();
goto done;
}
if (ev == QKeySequence::Redo)
{
ws->redo();
goto done;
}
if (ev->key() == Qt::Key_Return || ev->key() == Qt::Key_Enter)
{
QTextCursor cr = ws->textCursor();
Block *block = blockAtCursor(cr);
if (ev->modifiers() == 0 && isPromptBlock(block))
{
commitInput();
}
else if (ev->modifiers() == Qt::AltModifier ||
(ev->modifiers() == 0 && isOutputBlock(block)))
{
QString anchor = anchorAtCursor();
if (!anchor.isEmpty())
ws->activateUrl(anchor);
else
beep();
goto done;
}
else if (!(ev->modifiers() & ~Qt::ShiftModifier))
{
insertInteractive(ws, "\n", charFormat(), false);
goto done;
}
else
{
beep();
}
ev->accept();
//.........这里部分代码省略.........
示例11: parseData
void SourceEntryPrivate::parseData(const QString &data)
{
if (data.isEmpty())
return;
QString tData = data.simplified();
// Check for nonvalid input
if (tData.isEmpty() || tData == QChar('#')) {
isValid = false;
return;
}
// Check source enable state
if (tData.at(0) == '#') {
isEnabled = false;
}
// Handle multiple comment characters (hey, it happens!)
while (tData.size() > 0 && tData.at(0) == '#') {
// Remove starting '#' from tData
tData = tData.remove(0, 1);
tData = tData.trimmed();
}
// Find any #'s past the start (these are comments)
int idx = tData.indexOf('#');
if (idx > 0) {
// Save the comment, then remove from tData
comment = tData.right(tData.size() - idx - 1);
tData.remove(idx, tData.size() - idx + 1);
}
const QRegularExpression rx("^([a-z\\-]+) *");
QRegularExpressionMatch match = rx.match(tData);
// Parse type
type = match.captured(1);
const QSet<QString> types = { QLatin1String("rpm"), QLatin1String("rpm-src"), QLatin1String("deb"), QLatin1String("deb-src") };
if (!match.isValid() || !types.contains(type)) {
isValid = false;
return;
}
int start = match.capturedEnd(), end = tData.size();
// Parse architecture, see https://wiki.debian.org/Multiarch/HOWTO, Setting up sources
if (tData[start] == '[') {
QString metadata = tData.mid(start+1, tData.indexOf(']')-start-1);
QStringList options = metadata.split(';');
for (const QString &option : options) {
QStringList parts = option.split('=');
if (parts.size() != 2) {
isValid = false;
return;
}
QString key = parts.at(0);
if (key != QLatin1String("arch")) {
isValid = false;
return;
}
QString value = parts.at(1);
architectures = value.split(',');
}
start+=metadata.size()+2;
for (; tData[start] == ' '; ++start)
{}
}
bool inString = false;
bool done = false;
for (int i = start; !done && i<end; ++i) {
switch (tData[i].toLatin1()) {
case ' ':
if (!inString) {
uri = tData.mid(start, i-start);
start = i+1;
done = true;
} break;
case '[':
inString = true;
break;
case ']':
inString = false;
break;
}
}
if (uri.isEmpty() || !done) {
isValid = false;
return;
}
QStringList pieces = tData.mid(start).split(' ', QString::SkipEmptyParts);
if (pieces.isEmpty()) {
// Invalid source entry
isValid = false;
return;
}
//.........这里部分代码省略.........
示例12: generateEditorWithQrmc
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mLogicalRepoApi);
IdList const metamodels = mLogicalRepoApi->children(Id::rootId());
QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
int forEditor = 60 / metamodels.size();
foreach (Id const &key, metamodels) {
QString const objectType = key.element();
if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
QString nameOfPlugin = nameOfTheDirectory.split("/").last();
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading..")
, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
, QMessageBox::Yes, QMessageBox::No)
== QMessageBox::No)
{
continue;
}
progress->setValue(5);
if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("Cannot generate source code for editor ") + nameOfPlugin);
continue;
}
progress->setValue(20);
QProcess builder;
builder.setWorkingDirectory("../qrmc/plugins");
builder.start(SettingsManager::value("pathToQmake").toString());
qDebug() << "qmake";
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(40);
builder.start(SettingsManager::value("pathToMake").toString());
bool finished = builder.waitForFinished(100000);
qDebug() << "make";
if (finished && (builder.exitCode() == 0)) {
qDebug() << "make ok";
progress->setValue(progress->value() + forEditor / 2);
QString normalizedName = nameOfPlugin.at(0).toUpper() + nameOfPlugin.mid(1);
if (!nameOfPlugin.isEmpty()) {
if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("cannot unload plugin ") + normalizedName);
progress->close();
delete progress;
continue;
}
}
QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
+ nameOfPlugin
+ "."
+ SettingsManager::value("pluginExtension").toString()
;
if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
progress->setValue(progress->value() + forEditor / 2);
}
}
progress->setValue(100);
}
}
}
示例13: if
List::List(const QString &labelStr)
: QVector()
, _clean(true)
{
int labelPos = 0;
bool needsValue = true;
QRegExp rx;
while(labelPos < labelStr.length())
{
// Check if we want a value or if we're expecting either an end of
// string or a list value separator (:)
if(!needsValue)
{
if(labelStr.at(labelPos) == QChar(':'))
{
needsValue = true;
++labelPos;
continue;
}
else
{
qDebug() << "Unexpected char " << labelStr.at(labelPos) << " at "
<< "position " << labelPos << ", was expecting a list "
<< "value separator (:).";
_clean = false;
++labelPos;
continue;
}
}
else if(labelStr.at(labelPos) == QChar(':'))
{
// If we encounter one right after another value then add an empty
++labelPos;
push_back(ListValue("empty"));
continue;
}
if(labelStr.at(labelPos) == QChar('\'')
|| labelStr.at(labelPos) == QChar('"'))
{
QChar matched = labelStr.at(labelPos);
++labelPos;
int start = labelPos;
while(labelPos < labelStr.length()
&& labelStr.at(labelPos) != matched)
{
++labelPos;
}
int len = labelPos - start;
if(len == 0)
push_back(ListValue(Atom("")));
else
push_back(ListValue(Atom(labelStr.mid(start, len))));
if(labelPos < labelStr.length())
{
// We found a closing quote
++labelPos;
}
needsValue = false;
continue;
}
rx = QRegExp("[a-zA-Z0-9_][a-zA-Z0-9_]{,62}");
if(rx.indexIn(labelStr, labelPos) == labelPos)
{
QString identifier = rx.cap(0);
int matchLength = rx.matchedLength();
rx = QRegExp("\\d+");
if(rx.indexIn(labelStr, labelPos) == labelPos &&
rx.matchedLength() >= matchLength)
{
labelPos += rx.matchedLength();
QVariant num = rx.cap(0);
int value = num.toInt();
push_back(ListValue(Atom(value)));
needsValue = false;
continue;
}
labelPos += matchLength;
push_back(ListValue(identifier));
needsValue = false;
continue;
}
qDebug() << "Unexpected char " << labelStr.at(labelPos) << " at position "
<< labelPos << ", was expecting an atom or variable.";
_clean = false;
++labelPos;
}
}
示例14: parseString
void SM_Dropbox_Json::parseString(QString strJson)
{
#ifdef SM_QTDROPBOX_DEBUG
qDebug() << "parse string = " << strJson << endl;
#endif
// clear all existing data
emptyList();
// basically a json is valid until it is invalidated
valid = true;
if(!strJson.startsWith("{") ||
!strJson.endsWith("}"))
{
#ifdef SM_QTDROPBOX_DEBUG
qDebug() << "string does not start with { " << endl;
#endif
if(strJson.startsWith("[") && strJson.endsWith("]"))
{
#ifdef SM_QTDROPBOX_DEBUG
qDebug() << "JSON is anonymous array" << endl;
#endif
_anonymousArray = true;
// fix json to be parseable by the algorithm below
strJson = "{\"_anonArray\":"+strJson+"}";
}
else
{
valid = false;
return;
}
}
QString buffer = "";
QString key = "";
QString value = "";
bool isKey = true;
bool insertValue = false;
bool isJson = false;
bool isArray = false;
bool openQuotes = false;
for(int i=0; i<strJson.size(); ++i)
{
switch(strJson.at(i).toLatin1())
{
case '"':
if(!isKey)
{
buffer += "\"";
openQuotes = !openQuotes;
}
continue;
break;
case ' ':
if(!isKey)
buffer += " ";
continue;
break;
case '}':
if(openQuotes)
buffer += "}";
continue;
break;
case ':':
if(!isKey)
{
buffer += ":";
continue;
}
#ifdef SM_QTDROPBOX_DEBUG
qDebug() << "key = " << buffer << endl;
#endif
key = buffer.trimmed();
buffer = "";
isKey = false;
break;
case ',':
if(openQuotes)
{
buffer += ',';
continue;
}
#ifdef SM_QTDROPBOX_DEBUG
qDebug() << "value = " << buffer << endl;
#endif
value = buffer.trimmed();
buffer = "";
isKey = true;
insertValue = true;
break;
case '{':
if(i == 0)
continue;
if(!openQuotes)
//.........这里部分代码省略.........
示例15: prepareExec
QString SqlEditor::prepareExec(toSQLParse::tokenizer &tokens, int line, int pos)
{
int LastLine = line;
int LastOffset = pos;
int endLine, endCol;
if (ui.sqlTextEdit->lines() <= tokens.line())
{
endLine = ui.sqlTextEdit->lines() - 1;
endCol = ui.sqlTextEdit->lineLength(ui.sqlTextEdit->lines() - 1);
}
else
{
endLine = tokens.line();
if (ui.sqlTextEdit->lineLength(tokens.line()) <= tokens.offset())
endCol = ui.sqlTextEdit->lineLength(tokens.line());
else
{
endCol = tokens.offset();
}
}
ui.sqlTextEdit->setSelection(line, pos, endLine, endCol);
QString t = ui.sqlTextEdit->selectedText();
bool comment = false;
bool multiComment = false;
int oline = line;
int opos = pos;
int i;
for (i = 0;i < t.length() - 1;i++)
{
if (comment)
{
if (t.at(i) == '\n')
comment = false;
}
else if (multiComment)
{
if (t.at(i) == '*' &&
t.at(i + 1) == '/')
{
multiComment = false;
i++;
}
}
else if (t.at(i) == '-' &&
t.at(i + 1) == '-')
comment = true;
else if (t.at(i) == '/' &&
t.at(i + 1) == '/')
comment = true;
else if (t.at(i) == '/' &&
t.at(i + 1) == '*')
multiComment = true;
else if (!t.at(i).isSpace() && t.at(i) != '/')
break;
if (t.at(i) == '\n')
{
line++;
pos = 0;
}
else
pos++;
}
if (line != oline ||
pos != opos)
{
LastLine = line;
LastOffset = pos;
ui.sqlTextEdit->setSelection(line, pos, endLine, endCol);
t = t.mid(i);
}
return t;
}