作业1:通过对话框实现保存文件
- void burger::on_saveBtn_clicked()
- {
- //调用函数,获取文件路径
- QString filename = QFileDialog::getSaveFileName(this,
- "选择文件夹",
- "./",
- "Text File(*.txt)");
- if(filename.isNull())
- {
- QMessageBox::information(this,"提示","你取消了保存文件");
- return;
- }
-
- QString q = ui->textEdit->toPlainText();
- //实例化文件对象
- QFile file(filename);
- //判断文件是否正常打开
- if(!file.open(QFile::ReadWrite))
- {
- return;
- }
- QByteArray msg;
- msg.append(q);
- int a = file.write(msg);
- if(a == -1)
- {
- QMessageBox::warning(this,"警告","写入失败");
- return;
- }
- ui->textEdit->setText("");
- file.close();
- }
作业2:
用键盘实现上下左右移动一个label
- #include "burger.h"
- #include "ui_burger.h"
-
- burger::burger(QWidget *parent)
- : QWidget(parent)
- , ui(new Ui::burger)
- {
- ui->setupUi(this);
- QPixmap p(":/112.jpg");
- ui->label->setPixmap(p);
- ui->label->setScaledContents(true);
-
- }
-
- burger::~burger()
- {
- delete ui;
- }
-
- //键盘按下事件
- void burger::keyPressEvent(QKeyEvent *event)
- {
- switch (event->key()) {
- case 'W':
- {
- if(ui->label->y() <= 0 - ui->label->height())
- {
- ui->label->move(ui->label->x(),this->height());
- }
- ui->label->move(ui->label->x(),ui->label->y()-5);
- }break;
- case 'S':
- {
- if(ui->label->y() >= this->height())
- {
- ui->label->move(ui->label->x(),0-ui->label->height());
- }
- ui->label->move(ui->label->x(),ui->label->y()+5);
- }break;
- case 'A':
- {
- if(ui->label->x() <= 0 - ui->label->width())
- {
- ui->label->move(this->width(),ui->label->y());
- }
- ui->label->move(ui->label->x()-5,ui->label->y());
- }break;
- case 'D':
- {
- if(ui->label->x() >= this->width())
- {
- ui->label->move(0-ui->label->width(),ui->label->y());
- }
- ui->label->move(ui->label->x()+5,ui->label->y());
- }break;
- }
- }
- //键盘抬起事件
- void burger::keyReleaseEvent(QKeyEvent *event)
- {
-
- }
思维导图: