PDA

View Full Version : QFlags questions



elcuco
19th March 2010, 13:21
This is my fist time using QFlags and something is not working here. I am probably missing something very stupid and I need a second eye...

4428

Edit:
code is simple enough to put inline as well...


#include <QCoreApplication>
#include <QFlags>
#include <QDebug>

class foobar{
public:
enum MyFlag{
flag1, flag2, flag3
};
Q_DECLARE_FLAGS(MyFlags, MyFlag)

MyFlags m_state;

void setFlag( MyFlag f, bool enable){
if (enable)
m_state &= !f;
else
m_state |= f;
}

void toggleFlag( MyFlag f ){
setFlag( f, !m_state.testFlag(f) );
}

bool getFlag( MyFlag f){
return m_state.testFlag(f);
}
};

int main()
{
foobar f;
qDebug() << "Flags state" << f.getFlag( foobar::flag1 );
f.toggleFlag(foobar::flag1);
qDebug() << "Flags state" << f.getFlag( foobar::flag1 );
}

wysota
19th March 2010, 13:35
I think the enum should have proper values (i.e. powers of 2 - 1, 2, 4, 8, etc.) so that flags don't interfere with each other. You might also want Q_DECLARE_OPERATORS_FOR_FLAGS if something doesn't compile.

elcuco
19th March 2010, 13:40
'Ok, new version. Now I get the correct value (false) by default. This was done by the new default values of flags. still, after "toggle", I don't see the flags changing state:


#include <QCoreApplication>
#include <QFlags>
#include <QDebug>

class foobar{
public:
enum MyFlag{
flag1 = 1,
flag2 = 2,
flag3 = 4
};
Q_DECLARE_FLAGS(MyFlags, MyFlag)

MyFlags m_state;

void setFlag( MyFlag f, bool enable){
if (enable)
m_state &= !f;
else
m_state |= f;
}

void toggleFlag( MyFlag f ){
setFlag( f, !m_state.testFlag(f) );
}

bool getFlag( MyFlag f){
return m_state.testFlag(f);
}
};
Q_DECLARE_OPERATORS_FOR_FLAGS(foobar::MyFlags)


int main()
{
foobar f;
qDebug() << "Flags state" << f.getFlag( foobar::flag1 );
f.toggleFlag(foobar::flag1);
qDebug() << "Flags state" << f.getFlag( foobar::flag1 );
}

This is a run:


[elcuco@pinky ~/src/qt4-bugs/testing-flags] make && ./testing-flags
g++ -c -pipe -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i686 -mtune=atom -fasynchronous-unwind-tables -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -I/usr/lib/qt4/mkspecs/linux-g++ -I. -I/usr/include/QtCore -I/usr/include/QtGui -I/usr/include -I. -I. -o testing-flags.o testing-flags.cpp
g++ -Wl,-O1 -o testing-flags testing-flags.o -lQtGui -lQtCore -lpthread
Flags state false
Flags state false

edit:
arg.ssf?!#@ ?!@$!@$ .... there is a bug in the "toggle" method, this is why it was not working. Finding and fixing it is left to the reader as en exercise. Thanks wysota!

wysota
19th March 2010, 14:33
Lol.... ! != ~ ;)