Qt: How to implement QDialogButtonBox with QSignalMapper for non-standard button ??

后端 未结 2 1998
萌比男神i
萌比男神i 2021-01-21 21:10

I have a QDialogButtonBox with All Standard Button and Non Standard Buttons (QPushbutton added to create Non-Standard Buttons).

I can implement SignalMapper saperately f

2条回答
  •  旧巷少年郎
    2021-01-21 21:50

    You shouldn't need to use QSignalMapper with QDialogButtonBox.

    QSignalMapper is used to connect multiple signals to a single slot, and QDialogButtonBox already has a single signal that is emitted for all the buttons: clicked(QAbstractButton*).

    You could simply assign a value to the button with a map (QMap, std::map) or through a dynamic property:

    enum { MyRole1 = 1, MyRole2 }; // starting at 1 because an unset property would return 0
    ...
    userButton−>setProperty("ActionRole", MyRole1); // a cast to int might be needed here
    buttonBox->addButton(userButton, QDialogButtonBox::ActionRole);
    
    connect(this, SIGNAL(clicked(QAbstractButton*)), SLOT(dialogButtonClicked(QAbstractButton *button)));
    

    And in the slot, you would get the value back from the parameter passed by the signal:

    void MyClass::dialogButtonClicked(QAbstractButton *button) {
        StandardButton standardButton = buttonBox−>standardButton(button);
        switch(standardButton) {
        // Standard buttons:
        case QDialogButtonBox::Ok: 
            ... 
            break;
        case QDialogButtonBox::Abort: 
            ...
            break;
    
        // Non-standard buttons:
        case QDialogButtonBox::NoButton: 
           int actionRole = button->property("ActionRole").toInt();
           switch(actionRole) {
           case MyRole1: 
               ...
               break;
           case MyRole2: 
               ...
               break;
          default:
               // shouldn't happen
               break; 
           }
    
        }
    } 
    

提交回复
热议问题