QTextEdit foreach - c++

I'm making a simple code text editor in Qt where it picks up C++ keywords and colors them. I know that Qt has a foreach function, but how can I use it live with the QTextEdit that the user is typing into?
Here is what I have tried, where if I type the word Hi into the textEdit then it pops up in the debug. This didn't work.
QLinkedList<QTextEdit* > list;
QString str = "Hi";
foreach(str, list)
qDebug() << str;
I think I saw this idea somewhere on a forum, but again it didn't work. If you can help out, any suggestions are helpful! Thanks!
Edit:
Here's what I have now:
QString text = ui->textEdit->toPlainText();
QString str = "Hi";
foreach(str, text)
qDebug() << str;
Except qDebug() outputs Hi every time I print a character rather than when I print all of Hi

I have no idea why you have a list of QTextEdits but to get your code to compile, you have to do like below.
QLinkedList<QTextEdit*> list;
QTextEdit* textEdit = NULL;
foreach(textEdit, list)
qDebug() << textEdit->toPlainText();
The problem with your code is that you are trying to assign a QTextEdti* to a QString.
Answer to the question asked in the comment:
Connect textChanged() signal of textEdit to a slot.
connect(textEdit, SIGNAL(textChanged()), SLOT(onTextChanged()))
In the slot, split the text in textEdit with space character and iterate.
private void MyWnd::onTextChanged()
{
QStringList wordList = textEdit->toPlainText().split();
foreach (QString word, wordList )
{
qDebug() << word;
}
}

OMG you doing that completely wrong and asking for solution which doesn't help in your problem in fact it makes it even worse.
Also all you need is documented in Qt.
Check this Qt example.

Related

How to organize or extract info from a QByteArray

I have a programm that recieves a full block in a single QByteArray. This block is "divided" with 'carriage returns' followed by 'end lines' (\r\n). In the middle of all this junk I have a date. Most specifically in the third line (between the second and the third \r\n).
Every time I try to extract this date from the ByteArray I end up with some random junk. How to be more precise with the QByteArray?
What is the best way of extracting this date without altering my ByteArray? Take in consideration that I don't know the date and it can even be in the wrong format.
Just for understanding purposes, here is an example of my ByteArray:
RandomName=name\r\nRandomID=ID\r\nRandomDate=date\r\nRandomTime=time\r\nRandomWhatever=whatever(...)
EDIT:
Sorry for bad english.
Let's say I have the following text sent to me:
ProgName = Marcus
ProgID = 180
ProgDate = 15.01.16
ProgTime = 13:39
(More info)......
However, none of this information is useful to me... except the Date. Everything was stored in a single QByteArray (Let's call it 'ba'). So this is my ba:
ProgName(space)=(space)Marcus\r\nProgID(space)=(space)180\r\nProgDate(space)=(space)15.01.16\r\nProgTime(space)=(space)13:39\r\n (keeps going)
My problem is: Storing "15.01.16" (the "ProgDate") in a QString without altering or destroying ba.
There are a variety of ways, but try one of the following solutions.
1) using split()
foreach (auto subByte, yourByteArray.replace("\r\n", "\n").split('\n')) {
qDebug() << subByte;
foreach (auto val, subByte.split('=')) {
qDebug() << val;
}
}
2) using QRegularExpression/QRegularExpressionMatchIterator, making all pair(key, value)
QRegularExpression re("(\\w+)=(\\w+)");
QRegularExpressionMatchIterator i = re.globalMatch(yourByteArray);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
qDebug() << match.captured(0)<< match.captured(1) << match.captured(2);
}
3) using QRegularExpression/QRegularExpressionMatch
QRegularExpression re("(RandomDate)=(\\w+)");
QRegularExpressionMatch match = re.match(yourByteArray);
if (match.hasMatch())
qDebug() << match.captured(0)<< match.captured(1) << match.captured(2);

QT: Finding and replacing text in a file

I need to find and replace some text in the text file. I've googled and found out that easiest way is to read all data from file to QStringList, find and replace exact line with text and then write all data back to my file. Is it the shortest way? Can you provide some example, please.
UPD1 my solution is:
QString autorun;
QStringList listAuto;
QFile fileAutorun("./autorun.sh");
if(fileAutorun.open(QFile::ReadWrite |QFile::Text))
{
while(!fileAutorun.atEnd())
{
autorun += fileAutorun.readLine();
}
listAuto = autorun.split("\n");
int indexAPP = listAuto.indexOf(QRegExp("*APPLICATION*",Qt::CaseSensitive,QRegExp::Wildcard)); //searching for string with *APPLICATION* wildcard
listAuto[indexAPP] = *(app); //replacing string on QString* app
autorun = "";
autorun = listAuto.join("\n"); // from QStringList to QString
fileAutorun.seek(0);
QTextStream out(&fileAutorun);
out << autorun; //writing to the same file
fileAutorun.close();
}
else
{
qDebug() << "cannot read the file!";
}
If the required change, for example is to replace the 'ou' with the american 'o' such that
"colour behaviour flavour neighbour" becomes "color behavior flavor neighbor", you could do something like this: -
QByteArray fileData;
QFile file(fileName);
file.open(stderr, QIODevice::ReadWrite); // open for read and write
fileData = file.readAll(); // read all the data into the byte array
QString text(fileData); // add to text string for easy string replace
text.replace(QString("ou"), QString("o")); // replace text in string
file.seek(0); // go to the beginning of the file
file.write(text.toUtf8()); // write the new text back to the file
file.close(); // close the file handle.
I haven't compiled this, so there may be errors in the code, but it gives you the outline and general idea of what you can do.
To complete the accepted answer, here is a tested code. It is needed to use QByteArray instead of QString.
QFile file(fileName);
file.open(QIODevice::ReadWrite);
QByteArray text = file.readAll();
text.replace(QByteArray("ou"), QByteArray("o"));
file.seek(0);
file.write(text);
file.close();
I've being used regexp with batch-file and sed.exe (from gnuWin32, http://gnuwin32.sourceforge.net/). Its good enough for replace one-single text.
btw, there is not a simple regexp syntax there. let me know If you want to get some example of script.

QString splitting multiple delimiters

I'm having trouble splitting a QString properly. Unless I'm mistaken, for multiple delimiters I need a regex, and I can't seem to figure out an expression as I'm quite new to them.
the string is text input from a file:
f 523/845/1 524/846/2 562/847/3 564/848/4
I need each number seperately to put into an array.
Some codes....
QStringList x;
QString line = in.readLine();
while (!line.isNull()) {
QRegExp sep("\\s*/*");
x = line.split(sep);
Any pointers?
Cheers
Change your regular expression like this:
QRegExp sep("(\\s+|/)");
then x will have every number.
I found it quite useful to try out RegEx's interactively. Nowadays there are a lot of online tools even, for example: http://gskinner.com/RegExr/
You can put your search text there and play with the RegEx to see what is matched when.
You could use the strtok function, which split a QString with one or more different tokens.
It would be like this:
QString a = "f 523/845/1 524/846/2 562/847/3 564/848/4";
QByteArray ba = a.toLocal8Bit();
char *myString = ba.data();
char *p = strtok(myString, " /");
while (p) {
qDebug() << "p : " << p;
p = strtok(NULL, " /");
}
You can set as many tokens as you need. For further info visit the cplusplus page of this particular function. http://www.cplusplus.com/reference/cstring/strtok/
Regards!.

How do I insert a variable result into a string in C++

I just started learning C++ in Qt and I was wondering how can I put a variables result in a string? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence. I know in objective-c it would be like,
NSString *name = [NSString stringWithFormatting:#"Hello, %#", [nameField stringValue]];
[nameField setStringValue:name];
How would I go about doing something like this with C++? Thanks for the help
I assume we're talking about Qt's QString class here. In this case, you can use the arg method:
int i; // current file's number
long total; // number of files to process
QString fileName; // current file's name
QString status = QString("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);
See the QString documentation for more details about the many overloads of the arg method.
You donĀ“t mention what type your string is. If you are using the standard library then it would be something along the lines of
std::string name = "Hello, " + nameField;
That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this:
std::ostringstream stream;
stream << "Hello, " << nameField;
stream << ", here is an int " << 7;
std::string text = stream.str();
Qt probably has its own string types, which should work in a similar fashion.
I would use a stringstream but I'm not 100% sure how that fits into your NSString case...
stringstream ss (stringstream::in);
ss << "hello my name is " << nameField;
I think QString has some nifty helpers that might do the same thing...
QString hello("hello ");
QString message = hello % nameField;
You could use QString::sprintf. I haven't found a good example of it's use yet, though. (If someone else finds one, feel free to edit it in to this answer).
You might be interested in seeing information about the difference between QString::sprintf and QString::arg.

QString, remove labels and content?

message.Text() is a QString.
I want to remove some text.
The text can be:
Normal: "This is a text"
With a label: "<label1>something</label1>This is a text"
First, I find if the text has the label:
!message.Text().contains("<label1>", Qt::CaseInsensitive))
So, if it has, I want to remove the first part, to have a normal text "This is a text".
I tried this:
first=message.Text().indexOf("<label1>");
last=message.Text().lastIndexOf("</label1>");
message.Text().remove(first,last);
But I got Compiler Error C2663.
I also know that the message.Text().remove(QChar('<label1'), Qt::CaseInsensitive); is another way to do it. But in my case, the part between the label is unkwnow.
It can be <label1>something</label1> or <label1>oisdioadj</label> or <label1>7</label1>....
Any idea?
Regards.
Try the following:
#include <iostream>
using std::cout; using std::endl;
#include <QString>
int main()
{
QString message = "<label1>something</label1>This is a test";
const QString labelClose = "</label1>";
const int labelCloseSize = labelClose.size();
cout << "message: " << qPrintable(message) << endl;
const int closePosition = message.lastIndexOf(labelClose);
QString justText = message.remove(0, closePosition + labelCloseSize);
cout << "just text: " << qPrintable(justText) << endl;
}
My advice here: keep things simple in your code, it will help making things simple in your head.
It seems what you want to achieve is more related to strings, than to label.
I suggest you get the text from your label, then work on it independently, then associate it back to your label:
QString text = message.text();
/* Do whatever you need to do here with text */
message.setText(text);
Also, the error you're having is probably due to the fact that you try to modify directly message.text() which is a const reference: obviously you can't modify something that is const.
I believe what you try to achieve can be done using QString::replace(). You'll have to use regular expressions for that, so if you're not familiar with it, it might be difficult.