QT子窗口保存父窗口指针
时间: 2023-08-31 19:09:42 浏览: 58
可以通过以下步骤在子窗口中保存父窗口指针:
1. 在子窗口的头文件中添加一个指向父窗口的指针变量,例如:
```
class ChildWindow : public QDialog
{
Q_OBJECT
public:
explicit ChildWindow(QWidget *parent = nullptr);
private:
QWidget *m_parentWidget; // 父窗口指针变量
};
```
2. 在子窗口的构造函数中,将父窗口指针保存到成员变量中,例如:
```
ChildWindow::ChildWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::ChildWindow),
m_parentWidget(parent) // 保存父窗口指针
{
ui->setupUi(this);
}
```
现在,你就可以在子窗口中使用 `m_parentWidget` 指向父窗口了。
相关问题
Qt子窗口在父窗口显示不出来
可能是因为子窗口没有添加到父窗口中,或者没有设置子窗口的大小和位置。请参考以下代码示例:
```cpp
// 创建子窗口
QWidget *childWidget = new QWidget(parentWidget);
childWidget->setGeometry(50, 50, 200, 200);
// 显示子窗口
childWidget->show();
```
其中,parentWidget是父窗口的指针,childWidget是子窗口的指针。setGeometry函数用来设置子窗口在父窗口中的位置和大小,show函数用来显示子窗口。如果还是无法显示子窗口,可以检查一下子窗口的属性和布局是否正确。
QT子窗口如何调用父窗口的qmap
在Qt中,子窗口想要调用父窗口的QMap,可以通过以下方式实现:
1. 在父窗口中定义QMap,并提供一个公有的访问函数,用于获取QMap。
```c++
class ParentWindow : public QMainWindow
{
public:
ParentWindow(QWidget *parent = nullptr);
QMap<QString, QString>& getMap(); // 获取QMap的函数
private:
QMap<QString, QString> myMap; // QMap定义在父窗口中
};
```
2. 在子窗口中获取父窗口指针,然后通过父窗口指针调用父窗口的getMap()函数获取QMap。
```c++
class ChildWindow : public QDialog
{
public:
ChildWindow(QWidget *parent = nullptr);
private:
void someFunction(); // 在子窗口中调用父窗口QMap的函数
ParentWindow *parentWindow; // 父窗口指针
};
```
```c++
ChildWindow::ChildWindow(QWidget *parent) : QDialog(parent)
{
parentWindow = qobject_cast<ParentWindow*>(parent); // 获取父窗口指针
}
void ChildWindow::someFunction()
{
QMap<QString, QString>& myMap = parentWindow->getMap(); // 调用父窗口的getMap()函数获取QMap
// 使用myMap进行操作
}
```
注意,在获取父窗口指针时,可以使用qobject_cast()函数来获取,因为在Qt中,QWidget的父子关系被管理为一棵树形结构,可以通过qobject_cast()函数来获取指向父窗口的指针。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)