Question

I'm using qt creator to create a gui for an vtk aplication.

I've made a #define action and I want to assign that command to a QPushButton.

How do I make the button reproduce my define if pressed?

example. ui->pushButton->...

Was it helpful?

Solution

The easy way is to define a default reponse slot for your button. In your class definition (the same class that defines the pushButton) you can just create a default slot under the slots section.

class MyMainApplication : public QMainWindow
{
  Q_OBJECT

  public:
    MyMainApplication(QWidget *parent = 0);
    ~MyMainApplication();

   // More stuff in the public section (...)

  public slots:
    void on_pushButton_clicked();    // This is the important line

  // The remaining definitions in your class
};

Now you just program the on_pushButton_clicked() function in your class implementation and it will respond to the click on the button called pushButton.

The syntax for default slots is on_NAMEOFTHEWIDGET_NAMEOFTHESIGNAL.

With the default slots, the connection is made automatically. If you want to use a generic name for the slot you must make the connection manually. For instance, say that instead of on_pushButton_clicked() you want to use mySlot(). In the class definition you would type

(...)
public slots:
  void mySlot();
(...)

and in the class implementation, probably in the constructor, after the ui->setupUi(this); command you would make the connection of the button and your slot:

connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(mySlot()));

A final remark: in this particular case, I am almost sure that the slots can also be private.

OTHER TIPS

You need to use Qt's feature called Signals and Slots. Many objects can send signals when interacted with. Example is "clicked()" signal emitted from a QPushButton, or "triggered()" which is emitted upon clicking on QAction.

Main idea is to connect a signal to a slot. Slots are functions which are called when a signal is emitted. I can provide you with a PyQt example:

QtCore.QObject.connect(self.ui.myButton, QtCore.SIGNAL("clicked()"), self.someFunction)

C++ code shouldn't be much different. Check the Qt examples, they provide lots of good stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top