Reputation: 33813
My application is very simple, I have two buttons, the first button its text +
, and the second its text -
.
Then, I want when click on any one of buttons, I receive the text of button that I have clicked.
And the following is the method that called when click on any one of buttons.
void Widget::btns_clicked()
{
QPushButton *btn = dynamic_cast<QPushButton*>(sender());
char _operator = btn->text();
switch(_operator){
case '+':
QMessageBox::information(this, "Status", "You have clicked on (+)");
break;
case '-':
QMessageBox::information(this, "Status", "You have clicked on (-)");
break;
}
}
But appear the following error message:
cannot convert from 'QString' to 'char'
Also I have another small inquire
is there is any other simplest way to do that:
dynamic_cast<QPushButton*>(sender());
?
Upvotes: 0
Views: 2472
Reputation: 2770
btn->text() returns QString, which is not a native C++ type, so you have to convert it into std::string first. If you look at the QString docs (e.g. via Qt Assistant) you'll see there the toStdString() function that does just that:
std::string _operator = btn->text().toStdString();
Also, notice that I've used string instead of char as you cannot assign string to char. But that's no problem since string is just an array of char elements, and thus we can use _operator[0] in the switch:
switch(_operator[0]){
case '+':
...
That would solve your current problem and thus it ends the answer. One suggestion: why not use different slots for every button so that you immediately know which button has been clicked?
Also, you don't need a switch in your present code at all. You can just print information like this:
QMessageBox::information(this, "Status", "You have clicked on (" + _operator + ")");
and you'll always get the right message, no matter which button has been clicked.
Upvotes: 1