qt 子窗口某函数发送信号到父窗口,使父窗口关闭子窗口,c++示例
时间: 2023-07-19 15:17:40 浏览: 121
以下是一个简单的示例,演示如何在Qt中实现子窗口某函数向父窗口发送信号,使父窗口关闭子窗口:
MyChildWindow.h:
```cpp
#ifndef MYCHILDWINDOW_H
#define MYCHILDWINDOW_H
#include <QWidget>
class QPushButton;
class MyChildWindow : public QWidget
{
Q_OBJECT
public:
explicit MyChildWindow(QWidget *parent = nullptr);
signals:
void closeWindow();
private slots:
void closeWindowButtonClicked();
private:
QPushButton *closeWindowButton;
};
#endif // MYCHILDWINDOW_H
```
MyChildWindow.cpp:
```cpp
#include "MyChildWindow.h"
#include <QPushButton>
#include <QVBoxLayout>
MyChildWindow::MyChildWindow(QWidget *parent) : QWidget(parent)
{
closeWindowButton = new QPushButton("Close Window", this);
connect(closeWindowButton, &QPushButton::clicked, this, &MyChildWindow::closeWindowButtonClicked);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(closeWindowButton);
setLayout(layout);
}
void MyChildWindow::closeWindowButtonClicked()
{
emit closeWindow();
}
```
MainWindow.h:
```cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MyChildWindow;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void openChildWindow();
void closeChildWindow();
private:
MyChildWindow *childWindow;
};
#endif // MAINWINDOW_H
```
MainWindow.cpp:
```cpp
#include "MainWindow.h"
#include "MyChildWindow.h"
#include <QVBoxLayout>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
childWindow = nullptr;
QPushButton *openButton = new QPushButton("Open Child Window", this);
connect(openButton, &QPushButton::clicked, this, &MainWindow::openChildWindow);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(openButton);
QWidget *centralWidget = new QWidget(this);
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
}
MainWindow::~MainWindow()
{
if (childWindow != nullptr)
{
delete childWindow;
}
}
void MainWindow::openChildWindow()
{
if (childWindow == nullptr)
{
childWindow = new MyChildWindow(this);
connect(childWindow, &MyChildWindow::closeWindow, this, &MainWindow::closeChildWindow);
childWindow->show();
}
}
void MainWindow::closeChildWindow()
{
if (childWindow != nullptr)
{
childWindow->close();
delete childWindow;
childWindow = nullptr;
}
}
```
在这个示例中,`MyChildWindow`类表示子窗口,它包含一个名为"closeWindowButton"的按钮,当用户单击该按钮时,它会触发一个名为"closeWindow"的信号。该信号被定义为`void closeWindow()`,它表示要关闭窗口。
`MainWindow`类表示父窗口,它包含一个名为"openButton"的按钮,当用户单击该按钮时,它将创建`MyChildWindow`对象,并将其连接到该对象的"closeWindow"信号的`closeChildWindow`槽函数。当子窗口触发"closeWindow"信号时,`MainWindow`的`closeChildWindow`槽函数将被调用,它将关闭子窗口并删除子窗口对象。
阅读全文