PDA

View Full Version : Creating static const QColors



ToddAtWSU
20th December 2013, 21:21
I have a class where I declare some public static const QColors in my .h file:


class myClass
{
public:
...
static const QColor GREEN;
static const QColor BLUE;
static const QColor RED;
static const QColor ORANGE;
...
}

Then at the top of my .cpp file, I have:

const QColor myClass::GREEN = QColor(0, 204, 0);
const QColor myClass::BLUE = QColor(0, 102, 255);
const QColor myClass::RED = QColor( 255, 0, 0);
const QColor myClass::ORANGE = QColor(255, 153, 0);

Later, in a function inside myClass, when I try to say:


QColor newColor = myClass::GREEN; // Also tried QColor newColor = GREEN;
qDebug( ) << newColor;

It prints out that newColor is "QColor(Invalid)"

What is wrong with declaring these QColors this way?

ToddAtWSU
23rd December 2013, 19:36
Forgot to mention this is running Qt 4.8.5 since I am required to still provide support for Solaris 10. I am currently running into this problem on Windows 7 however.

ChrisW67
23rd December 2013, 22:57
This works as expected:


#include <QtGui>

class Class {
public:
static const QColor GREEN;
};

const QColor Class::GREEN = QColor(0, 255, 0);

int main(int argc, char **argv) {
QApplication app(argc, argv);
QColor test = Class::GREEN;
qDebug() << test << Class::GREEN;
return 0;
}

whether Class in defined in main.cpp or separate files.

Where is this code in your program?


QColor newColor = myClass::GREEN; // Also tried QColor newColor = GREEN;
qDebug( ) << newColor;

In main(), some non-static function, a static function, or the constructor of a class that you are creating static instances of? You may be falling foul of static initialisation order: http://www.parashift.com/c++-faq/static-init-order.html

ToddAtWSU
24th December 2013, 13:40
In main(), some non-static function, a static function, or the constructor of a class that you are creating static instances of? You may be falling foul of static initialisation order: http://www.parashift.com/c++-faq/static-init-order.html

Thanks a bunch. I had a couple static const class objects calling the constructor but they were declared prior to my static const QColors being called which your link explained to me right away that those probably had not been initialized yet. Moving the QColor declarations to the top fixed my issue! Thanks again!