PDA

View Full Version : How To do an actionListener



bod
27th June 2008, 10:12
Hello, I need to implement an action listener but i dont know much about signals and slots.
Let me explain what I'm trying to do:
In my program I have 2 views. User will select from the view action in the menubar. There are 2 views. When 1 is selected, it will be checked and the other will become unchecked.Also the view will change.
How can i implement this actionlistener??

AD
27th June 2008, 10:41
void MyClass::pressMenu()
{
QAction* your_action = qobject_cast<QAction*> (sender());
// Your code
}

By this action you get your action. Then you change view according to selected action! Their actions you should to do in the slot (for example it's name is pressMenu)!


class MyClass
{
// your variables and functions
QAction* myActions[2];
private slots:
void pressMenu();
}
- in header


for(int i=0; i<2; ++i)
{
myActions[i] = new QAction(this);
connect(myActions[i], SIGNAL(triggered()), this, SLOT(pressMenu()));
}
- in source
For example use this code!

jpn
27th June 2008, 12:18
See QActionGroup.

bod
27th June 2008, 12:23
Thank you very much, it works=)
but i did not understand what is this line for?
"QAction* your_action = qobject_cast<QAction*> (sender());"
I just put a print in the method and it prints it also without this line

AD
27th June 2008, 12:53
You can select needed action from array of actions by this method!

AD
27th June 2008, 12:58
For example, array considered two actions - "Open" and "New":


void MyClass::pressMenu()
{
QAction* your_action = qobject_cast<QAction*> (sender());
QString name_menu = your_action -> text();
}


If you click in "Open", mean of name_menu is "Open", other - "New"!

bod
27th June 2008, 13:07
Okey I get it. But I have another problem now. I have a menu at top. Like "File" menu in browser. In it, there are two actions: actionViewClassic, actionViewModern.
These are checkable. So if one of them is checked, the other one must be unchecked. To reach this goal,I passed the other Action as a parameter to the function.However since, I created the gui with designer, if i try to change the other buttons checked function it gives me an error Because of scoping. how can I accomplish these checkablity situation ??

Error:

GeneratedFiles\Debug\moc_assignment1.cpp(66) : error C2248: 'QAction::QAction' : cannot access private member declared in class 'QAction'
1> d:\qt\include\qtgui\../../src/gui/kernel/qaction.h(191) : see declaration of 'QAction::QAction'
1> d:\qt\include\qtgui\../../src/gui/kernel/qaction.h(41) : see declaration of 'QAction'

jpn
27th June 2008, 13:24
These are checkable. So if one of them is checked, the other one must be unchecked... how can I accomplish these checkablity situation ??
Take a look at QActionGroup as already proposed.