Here is my code:
const QString k_NoFilter = "No Filter";
const QString k_Filter1 = "UV filter";
QStringList filters;
filters << k_NoFilter << k_Filter1;
ui.comboFilter->addItems(filters);
int ix = ui.comboFilter->findText(k_NoFilter);
ui.comboFilter->setCurrentIndex(ix);
I can't get the index. It always is -1. What might be wrong?
This is because the string for the item is stored by Qt in a weird way. It is ended with two white spaces (maybe '\r' and '\n').
Related
How to remove /Job from /home/admin/job0/Job
QString name = "/home/admin/job0/Job"
I want to remove last string after"/"
You have QString::chop() for the case when you already know how many characters to remove.
It is same as QString::remove(), just works from the back of string.
Find last slash with QString::lastIndexOf.
After that get substring with QString::left till the position of the last slash occurrence
QString name = "/home/admin/job0/Job";
int pos = name.lastIndexOf(QChar('/'));
qDebug() << name.left(pos);
This will print:
"/home/admin/job0"
You should check int pos for -1 to be sure the slash was found at all.
To include last slash in output add +1 to the founded position
qDebug() << name.left(pos+1);
Will output:
"/home/admin/job0/"
Maybe easiest to understand for later readers would probably be:
QString s("/home/admin/job0/Job");
s.truncate(s.lastIndexOf(QChar('/'));
qDebug() << s;
as the code literaly says what you intended.
You can do something like this:
QString s("/home/admin/job0/Job");
s.remove(QRegularExpression("\\/(?:.(?!\\/))+$"));
// s is "/home/admin/job0" now
If you are using Qt upper than 6 and sure that "/" constains in your word you should use QString::first(qsizetype n) const function instead QString::left(qsizetype n) const
Example:
QString url= "/home/admin/job0/Job"
QString result=url.first(lastIndexOf(QChar('/')));
If you run these code:
QElapsedTimer timer;
timer.start();
for (int j=0; j<10000000; j++)
{
QString name = "/home/admin/job0/Job";
int pos = name.lastIndexOf("/");
name.left(pos);
}
qDebug() << "left method" << timer.elapsed() << "milliseconds";
timer.start();
for (int j=0; j<10000000; j++)
{
QString name = "/home/admin/job0/Job";
int pos = name.lastIndexOf(QChar('/'));
name.first(pos);
}
qDebug() << "frist method" << timer.elapsed() << "milliseconds";
Results:
left method 10034 milliseconds
frist method 8098 milliseconds
sorry for replying to this post after 4 years, but I have (I think) the most efficient answer.
You can use
qstr.remove(0, 1); //removes the first character
qstr.remove(1, 1); //removes the last character
Thats everything you have to do, to delete characters ONE BY ONE (first or last) from a QString, until 1 character remains.
I'd like to monitorize how RAM memory I used for may Qt application; so, I thought about something to put inside the code.
I tried the following:
QProcess p;
p.start("ps -A");
p.waitForFinished();
QByteArray RamMem =p.readAllStandardOutput();
p.close();
quint16 pidcounter = 0;
QString pidString(RamMem);
QStringList RamMemSplit = pidString.split('\n');
quint16 RamMemSplitcounter = RamMemSplit.count();
while(pidcounter< RamMemSplitcounter)
{
if (RamMemSplit[pidcounter].contains(MyApp))
{
splitsplit = RamMemSplit[pidcounter].split(" ");
qDebug() << "Process:"<< splitsplit[10]<< "pid:"<< splitsplit[0];
}
pidcounter++;
}
In this way, I save name of running process associated to its pid;
Now, I'd like to apply another process ("pmax -x mypid), so I can obtain the RAM amount of my app:
How can I perform this? I read a QProcess requires a QStringList argument; in my case, I have only one parameter to use as argument and it's no so clear how to correctly set tyhe QProcess. The following is my idea, connected to the previous part:
QStringList listprova(splitsplit[0]);
QProcess pr;
pr.start("pmap -x", listprova);
pr.waitForFinished();
QByteArray pmapResult = pr.readAllStandardOutput();
pr.close();
QString pmapString(pmapResult);
QStringList pmapSplit = pmapString.split('\n');
quint8 pmapCounter = pmapSplit.count();
qDebug() << pmapSplit[pmapCounter]; // last line of "pmap -x [pid]" console command
You have 2 arguments, -x and the pid.
QStringList arguments;
arguments << "-x" << splitsplit[0];
QProcess pr;
pr.start("pmap", arguments);
I have a Qt (4.7) program that takes a QByteArray and should break it into a list of QVariants, after using a parser to transform it into a QVariant. The problems seem to arise when I try to use the toList() function. I have something similar to this:
QVariant var = //whatever the value passed in is...
std::cout << "Data = " << var.toString().toStdString() << std::endl;
QList<QVariant> varlist = var.toList();
std::cout << "List Size = " << varlist.size() << std::endl;
which would return this:
Data = variant1 variant2 variant3
Size = 0
where the size should clearly be 3. Does anyone have an idea what I may be doing wrong? thanks!
The documentation of toList() says:
Returns the variant as a QVariantList if the variant has userType() QMetaType::QVariantList or QMetaType::QStringList; otherwise returns an empty list.
My guess is, your variant's userType() is neither of those two.
You probably need to construct your variant differently, e.g.
QVariantList list;
list << variant1 << variant2 << variant3;
QVariant var = list;
So, I have no idea why, but when I put the command I specified above into a separate function, ie QList<QVariant> myClass::ToList(QVariant v){return v.toList();}, and then call varlist = myClass::ToList(v), it works. Still doesn't the original way, but this way it's fine. Guess I'll just chalk it up to one of the quirks of Qt...
i need add on firt position of qbytearray a quint16 and after read it: How can i to do it?
I have try this:
quint16 pos = 0;
QFile file(m_pathFile);
if (file.open(QFile::ReadOnly))
{
qDebug() << "el fichero existe";
m_udpSocket->bind(m_port);
QByteArray datagram;
while (!file.atEnd())
{
datagram.begin();
datagram.append(pos++);
datagram = file.read(m_blockSize);
qDebug() << "Sec" << datagram.at(0);
}
}
Thanks you very much
I got add with:
datagram.begin();
datagram.setNum(pos, 10);
datagram.append(file.read(m_blockSize));
but i don't know as read it
Thanks
Ok, first of all, that datagram.begin() is useless since it returns an iterator that you don't assign at all. If you want to insert a number in the first position of a QByteArray you can do something like:
datagram.insert(0, QString::number(pos++));
To read it, the simplest way is to use a QTextStream like this:
QTextStream str(datagram);
quint16 num;
str >> num;
Also, take a look at the docs before posting, because the Qt ones are really simple and helpful if you know how to search (and it's not that difficult, trust me).
I've been using QString::number () to convert numbers to string for long time , now i'm wondering if there's something better than following:
int i = 0;
QString msg = QString ("Loading %1").arg (QString::number (i));
How can i spare QString::number () ? i checked document , seems only "%1" is applicable , no other stuff like "%d" could work
QString's arg() function does indeed implement many different types and automatically detect what you provide it. Providing multiple parameters to a single arg() call like so
// Outputs "one two three"
QString s = QString("%1 %2 %3").arg("one", "two", "three")
is only implemented for QString (and hence const char*) parameters.
However, you can chain arg calls together and still use the numbering system:
int i = 5;
size_t ui = 6;
int j = 12;
// Outputs "int 5 size_t 6 int 12"
qDebug() << QString("int %1 size_t %2 int%3").arg(i).arg(ui).arg(j);
// Also outputs "int 5 size_t 6 int 12"
qDebug() << QString("int %1 int %3 size_t %2").arg(i).arg(j).arg(ui);
You can directly use arg() like this
int i = 0;
QString msg = QString ("Loading %1").arg(i);
Qt will automatically convert it for you
Take a look at QString documentation. You have plenty of ::arg method overloads, that take different types. QString doesn't need to know what type will be under %n, method replacing that %n will know it and put proper value.