[QT] How to add a confirmation and cancel button to a custom Dialog, you can use the QDialogButtonBox class

If you want to obtain some business in the MainWindow interface when you press the OK key in the Dialog, for example, create a new project in the Mainwindow interface, pop up the dialog of the new project, and then display the information obtained in the New Project interface to the MainWindow interface, at this time, You need to send a signal in the Dialog, namely

//Dialog.h

//省略其他代码
//...
signal:
	emit signalOkClicked;
//Dialog.cpp 

//省略其他代码
//...
connect(btnOK, &QPushButton::clicked, this, &Dialoh::signalOkClicked);

Then, you can receive this signal in MainWindow and implement your own business in the slot function slotDiaOkClicked

//MainWindow.cpp

//...省略一些代码
Dialog* dialog = new Dialog(this);
connect(Dialog, &Dialog::signalOkClicked, this, &Mainwindow::slotDiaOkClicked)

Writing in this way feels cumbersome, and requires signal transmission, and then write the slot function after receiving it here.

At this time, you can use the QDialogButtonBox class to add buttons instead of directly using the QPushButton class to add buttons.

//Dialog.cpp

//其他布局省略
//...

//添加按钮
QDialogButtonBox* btnBox = new QDialogButtonBox(Qt::Horizontal, this);
QPushButton* btnOk = btnBox->addButton(tr("确定"), QDialogButtonBox::AcceptRole);
QPushButton* btnCancel = btnBox->addButton(tr("取消"), QDialogButtonBox::RejectRole);
btnOk->setMinimumHeight(28);
btnOk->setMinimumWidth(60);
btnCancel->setMinimumHeight(28);
btnCancel->setMinimumWidth(60);

The role of adding the role (QDialogButtonBox::AcceptRole) is to call exec() outside to determine the return result of QDialog

QDialogButtonBox can add a Role role to the button when adding a button. This is very important. In this way, when it is called outside, it can be used directly to if(dialog->exec()== QDialog::Accepted)determine which button the dialog is pressing, instead of connecting and sending a signal to the outside, so there is no need to receive confirmation. The connect function and slot function of the button.

//MainWindow.cpp

Dialog* dialog = new Dialog(this);
if(dialog->exec()== QDialog::Accepted){
    
      //表示按下的是确定键
	//实现自己的业务
	//...
}

Guess you like

Origin blog.csdn.net/WL0616/article/details/130231783