QStringPaint library released :)
-
Hi folks, i've made a library for fast transforming "raw" QStrings into colored by css/html.
https://github.com/ArtyMcLabin/QStringPaint
most primitive (and needed) usage example:#include "QStringPaint" QString resultMessage; if(foo()){ resultMessage = "a green success!"; ui->label1->setText(QStringPaint(resultMessage,Qt::green)); } else resultMessage = "a red error :("; ui->label1->setText(QStringPaint(resultMessage,"#ff0000"));
hope some of you will find it useful as i do :>
-
Thanks for sharing.
Couple of suggestions though:
-
For performance reasons avoid passing parameters by values or pointers. This is true even with implicitly shared types like QString. Passing it by value creates copies and is extremely bad for locality. Passing pointers is optimizer unfriendly. Always prefer a const reference if it's an "in" parameter or a non-const reference if it's an "in-out" parameter. Also avoid in-out parameters if possible and prefer returning a value. If you're interested in more details I recommend this excellent talk.
-
Again, for performance reasons concatenating strings like this is bad:
QString a = "foo" + someString + "bar"
. Prefer creating a string, callingreserve
with calculated length and then concatenating QLatin1String. A little worse, but also better than what you have is to create the string with placeholders and using thearg()
method, which does more or less the above. -
instead of taking an
int
parameter with a large switch case give it aconst QColor&
param and use its name() method to convert it to css compatible string. Since QColor has a constructor overloads for various types this would work with various parameters likeQColor::fromRgb(128,128,128)
,Qt::red
,0xFF6633
etc. -
Just a stylistic note: QSomeName for Qt users suggests a class name. Lowercase is preferred for function names in Qt api. Since it's not part of official Qt package I would also avoid the Q name entirely.
So an optimized interface for this would look like this:
QString stringPaint(const QString& str, const QString& color); QString stringPaint(const QString& str, const QColor& color);
I would also consider adding an overload for
const char*
andconst QLatin1String&
. -
-
@Chris-Kawa said:
t by value creates copies and is extremely bad for locality. Passing pointers is optimizer unfriendly. Always prefer a const referenc
thanks for the advices! i will start working on it.