获取输入内容

上一节中我们创建了一个文本框,然后之前也为按钮绑定了事件使按钮点击时弹出对话框,所以我们可以获取输入的内容并且用对话框显示出来。

我们上节创建文本框的代码是这样的:

QLineEdit* lineEdit = new QLineEdit(this );
lineEdit->setGeometry(200, 130, 200, 50);

它使用的是一个局部变量,我们只能在内部访问它。要在我们的函数中使用,就必须将它定义为成员变量。

在MyFirstQt6.h中,我们添加

private :
QLineEdit* lineEdit;

完整如下:

#pragma once
#include <QtWidgets/QMainWindow>
#include <QtWidgets>

class MyFirstQt6 : public QMainWindow
{
Q_OBJECT

public :
MyFirstQt6(QWidget *parent = nullptr);
~MyFirstQt6();

private slots:
void onButtonClicked ();

private :
QLineEdit* lineEdit;
};

使其成为MyFirstQt6的成员变量

同时要将之前创建控件的代码修改成

lineEdit = new QLineEdit(this );
lineEdit->setGeometry(200, 130, 200, 50);

回到之前的函数中

我们可以使用text()方法获取文本框的内容

QString text = lineEdit->text ();
QMessageBox::information(this, "信息", "你输入的内容是: " + text);

当我们输入内容后点击按钮就会显示出输入的内容

完整代码

#include "MyFirstQt6.h"
#include <QtWidgets>

MyFirstQt6::MyFirstQt6(QWidget* parent)
: QMainWindow(parent)
{
setWindowTitle("第一个Qt6窗口");
resize(600, 400);

QLabel* label = new QLabel(this);
label->setText("这是一个标签控件");
label->setGeometry(200, 30, 200, 50);

QPushButton* button = new QPushButton(this);
button->setText("这是一个按钮控件");
button->setGeometry(200, 80, 200, 50);
connect(button, &QPushButton::clicked, this, &MyFirstQt6::onButtonClicked);

lineEdit = new QLineEdit(this);
lineEdit->setGeometry(200, 130, 200, 50);
}

MyFirstQt6::~MyFirstQt6()
{}

void MyFirstQt6::onButtonClicked()
{
QString text = lineEdit->text();
QMessageBox::information(this, "信息", "你输入的内容是: " + text);
}

相关推荐
qq_589666057 分钟前
C语言、C++与C#的区别详解
c语言·c++·c#
万法若空30 分钟前
排列组合恒等式
c++·算法
Data_Journal32 分钟前
如何使用 Python 抓取 Google Flights:分步指南
大数据·开发语言·数据库·python·scrapy
一直C1 小时前
【数据结构】哈希表+算法复杂度与经典排序查找(C语言)
java·linux·开发语言·数据结构·算法·ubuntu·散列表
Kismet_nvi1 小时前
Python 基础核心知识点总结
开发语言·windows·python
爱学习的小邓同学1 小时前
Golang语言入门
开发语言·后端·golang
老洋葱Mr_Onion1 小时前
【C++】CSP-J初赛模拟卷七错题整理(作者自用)
c++·算法·深度优先
编码浪子2 小时前
Rust 智能指针深度实战:Box/Rc/Arc/RefCell 选型决策与内存管理避坑
开发语言·后端·rust
yichudu2 小时前
Python 装饰器 decorator
开发语言·python
电商API_180079052472 小时前
速卖通商品采集API技术文章
java·开发语言·c++·api·跨境电商·商品详情