(下方是编写程序的思想)
一、界面设计
1. 创建主窗口
- 通过继承`QWidget`类创建一个自定义的窗口类`GreetingCardGenerator`,并设置窗口标题为“中秋节贺卡生成器”。
2. 布局设置
- 使用`QVBoxLayout`垂直布局管理器来组织界面元素。
- 依次添加收卡人姓名标签和输入框、发卡人姓名标签和输入框、祝福信息标签和文本编辑框 以及“生成贺卡”按钮。
二、信号与槽连接
1. 按钮点击响应
- 将“生成贺卡”按钮的`clicked`信号与自定义槽函数`generateCard`连接,以便在按钮被点击时执行 生成贺卡的操作。
三、生成贺卡功能
1. 获取用户输入
- 在`generateCard`槽函数中,通过输入框和文本编辑框的对象获取用户输入的收卡人姓名、发卡 人姓名和祝福信息。
2. 写入文件
- 尝试打开名为“mid_autumn_card.txt”的文件进行写入操作。如果文件成功打开,使用 `QTextStream`将贺卡的格式内容以及用户输入的信息写入文件。
- 内容包括固定的边框、贺卡标题、收卡人称呼、祝福信息、发卡人信息等。
3. 反馈结果
- 如果文件写入成功,弹出信息框告知用户“贺卡生成成功!”;如果出现错误,弹出错误信息框“无法生成贺卡。”。
四、主函数
1. 初始化应用程序
- 在`main`函数中,创建`QApplication`对象来初始化 Qt 应用程序。
2. 创建并显示窗口
- 创建`GreetingCardGenerator`对象表示贺卡生成器窗口,并调用`show`方法显示窗口。
3. 启动应用程序
- 返回`app.exec()`启动应用程序的事件循环,等待用户操作。
(下方是可实现C++程序)
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
class GreetingCardGenerator : public QWidget {
public:
GreetingCardGenerator() {
setWindowTitle("中秋节贺卡生成器");
QVBoxLayout *layout = new QVBoxLayout();
QLabel *recipientLabel = new QLabel("收卡人姓名:");
recipientEdit = new QLineEdit();
layout->addWidget(recipientLabel);
layout->addWidget(recipientEdit);
QLabel *senderLabel = new QLabel("发卡人姓名:");
senderEdit = new QLineEdit();
layout->addWidget(senderLabel);
layout->addWidget(senderEdit);
QLabel *messageLabel = new QLabel("祝福信息:");
messageEdit = new QTextEdit();
layout->addWidget(messageLabel);
layout->addWidget(messageEdit);
generateButton = new QPushButton("生成贺卡");
layout->addWidget(generateButton);
connect(generateButton, &QPushButton::clicked, this, &GreetingCardGenerator::generateCard);
setLayout(layout);
}
private slots:
void generateCard() {
QString recipient = recipientEdit->text();
QString sender = senderEdit->text();
QString message = messageEdit->toPlainText();
QFile file("mid_autumn_card.txt");
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&file);
out << "-------------------------\n";
out << " 中秋佳节贺卡\n";
out << "-------------------------\n\n";
out << "亲爱的 " << recipient << ":\n\n";
out << message << "\n\n";
out << "来自:" << sender << "\n";
out << "-------------------------\n";
file.close();
QMessageBox::information(this, "成功", "贺卡生成成功!");
} else {
QMessageBox::critical(this, "错误", "无法生成贺卡。");
}
}
private:
QLineEdit *recipientEdit;
QLineEdit *senderEdit;
QTextEdit *messageEdit;
QPushButton *generateButton;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
GreetingCardGenerator generator;
generator.show();
return app.exec();
}
注意:此程序仅供参考,其他内容可自行编写或者在私信询问作者
作者允许粉丝定制或安排下次博客内容哦!
作者主页:https://blog.csdn.net/wgiwgi_______?spm=1010.2135.3001.5343