How to make a QPushButton disabled
I created lots of QPushButtons, added clicked signal and a slot name ´deneme()´ to all of the buttons with QT DESIGNER
and the thing I wa开发者_开发技巧nt to do is; when I clicked any button, some operation should be done and lastly the button should be disabled but we do not know which button is clicked. I know I can disable the buttons with setEnabled()
and isEnabled()
but I do not know how to disable them.
If I understood correctly you connected various QPushButtons
to the same slot. Inside of the slot deneme()
you want to know which of the buttons was clicked
.
You can do something like:
void deneme() {
QPushButton * b = qobject_cast<QPushButton *>(sender());
if (b) {
if (b == button1) { //button1 clicked
//doSomething();
}
else {
if (b == button2) {
//doSomething();
}
}
b->setEnabled(false);
}
}
Why is setEnabled not working then? The reference.
So a simple setEnabled(false); is enough.
QPushButton* button = new QPushButton(someParent);
button->setEnabled(false);
If the connecting a event handler on the click event of the button maybe you should look at the QT documentation: Signal and slots
You mean Button has to be disabled right after clicking on it? I guess in that case you probably want to do something like this:
class MyWidget : public QWidget
{
Q_OBJECT
// ...
private slots:
void disableButton();
private:
QPushButton *myButton;
// ...
};
MyWidget::MyWidget(QWidget *parent = NULL) : QWidget(parent)
{
///...
myButton = new QPushButton("click me", this);
connect(myButton, SIGNAL(clicked), this, SLOT(disableButton));
// ...
}
void MyWidget::disableButton()
{
myButton->setEnabled(false);
}
Bruno's answer is correct.
sender();
returns a QObject*
You can cast it to a QPushButton*
using either
C Style cast i.e QPushButton* clickedButton = (QPushButton*)(sender())
or
QPushButton* clickedButton = static_cast<QPushButton*>(sender())
or
QPushButton * clickedButton = qobject_cast(sender());
as far as i know qobject_cast works similar to dynamic_cast<> in C++. But if you are having compilation problems any solution given above should work fine.
精彩评论