C++Qt点击OK、Apply、cencel的button按钮,响应mainwindow事件
时间: 2023-07-10 16:38:16 浏览: 103
在C++Qt中,可以通过信号槽机制在按钮被点击时向主窗口发送信号,然后在主窗口中实现对应的槽函数来响应这些事件。具体实现步骤如下:
1. 在主窗口的头文件中声明三个槽函数:onOkClicked()、onApplyClicked()和onCancelClicked()。
```cpp
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
private slots:
void onOkClicked();
void onApplyClicked();
void onCancelClicked();
};
```
2. 在主窗口的构造函数中创建按钮,并连接它们的clicked()信号到对应的槽函数。
```cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QPushButton *btnOk = new QPushButton(tr("OK"), this);
QPushButton *btnApply = new QPushButton(tr("Apply"), this);
QPushButton *btnCancel = new QPushButton(tr("Cancel"), this);
connect(btnOk, &QPushButton::clicked, this, &MainWindow::onOkClicked);
connect(btnApply, &QPushButton::clicked, this, &MainWindow::onApplyClicked);
connect(btnCancel, &QPushButton::clicked, this, &MainWindow::onCancelClicked);
// layout initialization and widget placement
}
```
3. 在主窗口的实现文件中实现三个槽函数,以响应按钮被点击的事件。
```cpp
void MainWindow::onOkClicked()
{
// Do something when OK button is clicked
}
void MainWindow::onApplyClicked()
{
// Do something when Apply button is clicked
}
void MainWindow::onCancelClicked()
{
// Do something when Cancel button is clicked
}
```
这样,当用户点击OK、Apply、Cancel按钮时,对应的槽函数将会被触发,从而实现了响应mainwindow事件的功能。
阅读全文
相关推荐










