3

New to QT just playing around with it to see if its something I will enjoy using and if so would like to go on and learn the program in depth.

Struggling a bit with the button concept. I have created a button and a textedit area. I want to add a string of text into the textedit window when the button is pressed.

I can't seem to find anything on google or the QT wiki to achieve this. Can someone point me in the direction so I can at least get started and have a play with this great tool.

1 Answer 1

6

In Qt signals and slots are being used to communicate between the objects. This should provide you with the necessary information to get you started.

A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal. Qt's widgets have many pre-defined slots, but it is common practice to subclass widgets and add your own slots so that you can handle the signals that you are interested in.

So, in your particular case you need to connect the QPushButton clicked() signal with your custom slot that does what is needed (add the text to the textarea):

 QPushButton * btn = new QPushButton("Button", this);
 connect(btn, SIGNAL(clicked()), this, SLOT(onBtnClicked()));

And we need to declare our slot in the header:

 private slots:
     void onBtnClicked();

And define it:

 void MySpecialWidget::onClick() 
 {
     // Do what is to be done
 }

If you have done everything correctly it should work... Otherwise have a look at the console to see if there are any messages looking like:

Object::connect: No such slot MySpecialWidget::onClick() in ...

or

Object::connect: No such signal ....

They should give you a hint about what is going on.

Finally I recommend to have a look at the broad set of Qt examples.

2
  • 1
    @twigg - just to add to Anonymous's answer. It looks odd at first but all Gui programming is odd at first. The Qt Signal/Slot is much better than most other approaches - just stick with it Apr 17, 2012 at 21:45
  • Thank you a lot of really good information this has really got me going now thanks a lot
    – twigg
    Apr 29, 2012 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.