tags:

views:

606

answers:

2

I just started using QtCreator tonight, and it seems it puts all of the interface stuff inside of the ui file. I followed a tutorial to create a resource for my icons, then I added them to a menu bar at the top. I need to make a connection when one of them is clicked though, and cannot figure out how to make a callback for it. Am I going to have to completely create them through code or is there someway to add a callback for them (rather than just making them interact with other objects).

A: 

To do that you'll need to add a QAction, add it to the menu, associate an icon with it and then create a callback for it. I'm using the VS Integration so I don't know the details of how to do it in Creator but it should be possible without creating stuff in code.

There should be somewhere an actions editor. from there you add an action, then right-click it or something to add an icon to it, then drag it do the menu and then possibly double click it to create a slot for it. This is how it works in the VS Integration atleast.

shoosh
+4  A: 

Menu bar items are action objects. To do something when they are clicked, you need to catch the triggered() signal from the action. Read more about signals and slots here.

To do this, you need to declare a new slot in your MainWindow class. Qt also supports doing this automatically, without the need to connect anything, but I prefer doing it myself. If you're not interested, just skip this part.

First, we declare a new slot in your window class:

private slots:
  void clickMenuButton();

Then, in your constructor, you need to connect the triggered signal to your new slot:

connect(ui.actionObject, SIGNAL(triggered()), this, SLOT(clickMenuButton()));

The first argument is the object that holds the signal we'll listen to (your menu button). The second is the name of the signal. The third is the object that holds the receiving slot (in this case, our window). The fourth is the slot.

And just like that, clickMenuButton() will be called whenever the action is clicked.

As I said before, Qt can also automatically connect signals to slots. The disadvantage here seems to be that you can't change the slot's name, but you don't need to connect it either.

Qt Creator supports creation of slots for widgets: in the case of your menu action, you should go to the form designer, and you should see a list of actions in your form (if you don't, find the Action Editor). Right click the action you want, and push Go to slot.... There, double click triggered().

Qt Creator will then open the new slot in your code editor, and you can do whatever you want to here!

Veeti
Thank you so much, this was perfect!
Brett Powell