Qt5 C++ 通过构造函数向子窗体传递参数demo
该程序包含两个窗口:
MainWindow(主窗口):包含一个按钮,点击后创建并显示子窗口,同时通过构造函数传递一个整数(例如 100)。
SubWindow(子窗口):接收主窗口传递的整数,并在界面上显示出来。
1. 子窗口代码 (SubWindow)
subwindow.h
#ifndef SUBWINDOW_H
#define SUBWINDOW_H
#include <QWidget>
#include <QLabel>
class SubWindow : public QWidget
{
Q_OBJECT
public:
// 构造函数:声明接收一个整型变量
explicit SubWindow(int value, QWidget *parent = nullptr);
~SubWindow();
private:
QLabel *label; // 用于显示接收到的数值
};
#endif // SUBWINDOW_H
subwindow.cpp
#include "subwindow.h"
#include <QVBoxLayout>
SubWindow::SubWindow(int value, QWidget *parent)
: QWidget(parent)
{
// 设置窗口标题
this->setWindowTitle("子窗口");
this->resize(300, 200);
// 创建标签
label = new QLabel(this);
// 将传入的整型变量转换为字符串并设置给标签
// QString::number(value) 是 Qt 中将 int 转为 QString 的常用方法
label->setText(QString("接收到的整数为: %1").arg(value));
// 简单的布局,让标签居中
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label);
this->setLayout(layout);
}
SubWindow::~SubWindow()
{
}
2. 主窗口代码 (MainWindow)
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
// 按钮点击的槽函数
void onOpenSubWindowClicked();
private:
QPushButton *btnOpen; // 按钮指针
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "subwindow.h" // 必须包含子窗口的头文件
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
this->setWindowTitle("主窗口");
this->resize(400, 300);
// 创建按钮
btnOpen = new QPushButton("打开子窗口并传值", this);
btnOpen->move(100, 100);
btnOpen->resize(200, 50);
// 连接信号与槽:点击按钮 -> 执行 onOpenSubWindowClicked
connect(btnOpen, &QPushButton::clicked, this, &MainWindow::onOpenSubWindowClicked);
}
MainWindow::~MainWindow()
{
}
// 槽函数实现
void MainWindow::onOpenSubWindowClicked()
{
int dataToSend = 100; // 定义要传递的整型变量
// 实例化子窗口,并通过构造函数传递变量
// 注意:这里将 this 设为父对象,虽然对于独立窗口不是必须的,但有助于内存管理
SubWindow *subWin = new SubWindow(dataToSend, this);
// 显示子窗口
subWin->show();
}目录 返回
首页