How can I fill with zeros at left? My code is:
QString reelId = QString("Month %1").arg(QDate::currentDate().month());
qDebug() << reelId;
and out is: Month 2 and I want Month 02;
The term you're really looking for is "pad", as in padding a string with something. Look through the QString documentation for this, specifically the various QString::arg() functions, which describes how to achieve this in a variety of ways :)
Have a look at QString::rightJustified()
QString reelId = QString( "Month %1" ).arg(
QString::number( QDate::currentDate().month() ).rightJustified( 2, '0' )
);
Another useful trick is to use QDate's toString() method thus:
QString reelId = QDate::currentDate().toString( "'Month' MM" );
The single quotes around "Month" prevent the word being interpreted as a placeholder.
Related
To keep a Stylesheet dynamic regarding DPI settings, I want to set certain parts of it from code.
This works:
my_label->setStyleSheet( QString( "font-size: 30px;" ) );
Yet, this doesn't:
my_label->setStyleSheet( QString( "font-size: %1px;" ).arg( 30 ) );
Can anyone enlighten me, why this is? Running Qt 5.7.
The issue was a combination of two things:
I needed to convert the value to a string first
The actual value passed to the arg() during runtime had a decimal place, the "30" was just for testing
While I did try different combinations (integer values (30), converting to QString first), I did not try using an integer value AND converting it to QString together.
So everyone was kinda right. Thanks for the patience.
Conver the number to a string, QString::number:
my_label->setStyleSheet(QString("QLabel{font-size: %1 px;}").arg(QString::number(30));
Or try it by using QFont, use this generic function for this purpose:
void updateFontSize(QLabel* label, int fontSize) {
QFont font = label->font();
if (font.pointSize() != fontSize) {
font.setPointSize(fontSize);
label->setFont(font);
}
}
I'm trying to add syntax completion to a QTextEdit base editor and I'd like to support non-alpha characters to trigger the QCompleter popup. I'm using QTextCursor::select to get the current word but it is always filtering out non-alpha characters. Is there an option I need to use for this ?
Here's the code I use to get the text:
QTextCursor tc = textCursor();
tc.select(QTextCursor::WordUnderCursor);
QString t = tc.selectedText();
thanks
Words actually do not contain alpha characters. To select the last input character:
QTextCursor tc = textCursor();
tc.movePosition ( QTextCursor::Left, QTextCursor::KeepAnchor);
QChar lastChar = tc.selectedText().at(0);
if (!lastChar.isLetterOrNumber())
{
do something;
}
Replace the isLetterOrNumber() with whatever characters you might check for.
I'm trying to write code that appends ending _my_ending to the filename, and does not change file extension.
Examples of what I need to get:
"test.bmp" -> "test_my_ending.bmp"
"test.foo.bar.bmp" -> "test.foo.bar_my_ending.bmp"
"test" -> "test_my_ending"
I have some experience in PCRE, and that's trivial task using it. Because of the lack of experience in Qt, initially I wrote the following code:
QString new_string = old_string.replace(
QRegExp("^(.+?)(\\.[^.]+)?$"),
"\\1_my_ending\\2"
);
This code does not work (no match at all), and then I found in the docs that
Non-greedy matching cannot be applied to individual quantifiers, but can be applied to all the quantifiers in the pattern
As you see, in my regexp I tried to reduce greediness of the first quantifier + by adding ? after it. This isn't supported in QRegExp.
This is really disappointing for me, and so, I have to write the following ugly but working code:
//-- write regexp that matches only filenames with extension
QRegExp r = QRegExp("^(.+)(\\.[^.]+)$");
r.setMinimal(true);
QString new_string;
if (old_string.contains(r)){
//-- filename contains extension, so, insert ending just before it
new_string = old_string.replace(r, "\\1_my_ending\\2");
} else {
//-- filename does not contain extension, so, just append ending
new_string = old_string + time_add;
}
But is there some better solution? I like Qt, but some things that I see in it seem to be discouraging.
How about using QFileInfo? This is shorter than your 'ugly' code:
QFileInfo fi(old_string);
QString new_string = fi.completeBaseName() + "_my_ending"
+ (fi.suffix().isEmpty() ? "" : ".") + fi.suffix();
I have a code someone wrote and there
this->llBankCode = new widgetLineEditWithLabel(tr("Bankleitzahl"), "", Qt::AlignTop, this);
QRegExpValidator *validatorBLZ = new QRegExpValidator(this);
validatorBLZ->setRegExp(QRegExp( "[0-9]*", Qt::CaseSensitive));
this->llBankCode->lineEdit->setValidator(validatorBLZ);
as it can be seen from this code, is that validatorBLZ can accept only numbers between 0 and 9. I would like to change it, that validatorBLZ would be able to get as an input whitespace as well (but not to start with a whitespace), but it wont be shown.
Example:
if i try to copy & paste a string of the format '22 34 44', the result would be an empty field. What i would like to happen is that the string '22 34 44' will be shown in the field as '223444'.
How could i do it?
You could try using:
QString string = "22 34 44";
string.replace(QString(" "), QString(""));
That will replace any spaces with a non-space.
Write your own QValidator subclass and reimplement validate and fixup. Fixup does what you ask for: changes the input in a way that makes it intermediate/acceptable.
In your case, consider the following code-snippet for fixup:
fixup (QString &input) const
{
QString fixed;
fixed.reserve(input.size());
for (int i=0; i<input.size(); ++i)
if (input.at(i).isDigit()) fixed.append(input.at(i));
input = fixed;
}
(this is not tested)
The validate function will obviously look similar, returning QValidator::Invalid when it encounters a non-digit character and returning the according position in pos.
If your BLZ is limited to Germany, you could easily add the validation feature that it only returns QValidator::Acceptable when there are eight digits, and QValidator::Intermediate else.
Anyhow, writing an own QValidator, which often is very easy and straight forward, is the best (and most future-proof) solution most of the time. RegExes are great, but C++ clearly is the more powerful language here, which in addition results in a much more readable validator ;).
I've got a string like so
Jamie(123)
And I'm trying to just show Jamie without the brackets etc
All the names are different lengths so I was wondering if there was a simple way of replacing everything from the first bracket onwards?
Some others are displayed like this
Tom(Test(123))
Jack ((4u72))
I've got a simple replace of the bracket at the moment like this
mystring.Replace("(", "").Replace(")","")
Any help would be appreciated
Thanks
VB.NET
mystring.Substring(0, mystring.IndexOf("("C)).Trim()
C#
mystring.Substring(0, mystring.IndexOf('(')).Trim();
One logic; get the index of the ( and you can trim the later part from that position.
public static string Remove(string value)
{
int pos = value.IndexOf("(");
if (pos >= 0)
{
return value.Remove(pos, remove.Length);
}
return value;
}
aneal's will work. The alternative I generally use because it's a bit more flexible is .substring.
string newstring = oldstring.substring(0,oldstring.indexof("("));
If you aren't sure that oldstring will have a "(" you will have to do the test first just as aneal shows in their answer.
String.Remove(Int32) will do what you need:
Deletes all the characters from this string beginning at a
specified position and continuing through the last position.
You will also have to .Trim() as well given the data with padding:
mystring = mystring.Remove(mystring.IndexOf("("C))).Trim()