1.完成自定义的记事本文件的保存功能
cpp
-------------------------------------------------------------------------
widget.cpp
-------------------------------------------------------------------------
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
//字体按钮对应的槽函数
void Widget::on_fontbtn_clicked()
{
//调用QFontDialog中的成员函数getFont函数来获取系统提供的字体对话框
bool ok; //接收用户是否选择字体
QFont font = QFontDialog::getFont(&ok,QFont("隶书",14,14,0),this,"选择字体");
if(ok == 1) //选中了字体
{
//将字体设置到文本上
//ui->textEdit->setFont(font);
//将字体设置到选中文本上
ui->textEdit->setCurrentFont(font);
}
else //未选中字体
{
QMessageBox::information(this,"提示","未选择字体");
}
}
void Widget::on_colbtn_clicked()
{
QColor col = QColorDialog::getColor(QColor("black"),this,"颜色选择");
if(col.isValid())//颜色合法
{
//ui->textEdit->setTextColor(col);
ui->textEdit->setTextBackgroundColor(col);
}
else //颜色不合法
{
QMessageBox::information(this,"提示","颜色不合法");
}
}
void Widget::on_openbtn_clicked()
{
QString fname = QFileDialog::getOpenFileName(this,
"选择文件",
"./",
"Image File(*.png *.jpg *.bmp);;Text File(*.txt);;All(*.*)");
if(fname.isNull())
{
QMessageBox::information(this,"文件选择","取消选择");
}
else
{
QFile rf(fname);
if(!rf.exists())
{
return;
}
if(!rf.open(QFile::ReadWrite))
{
return;
}
QByteArray msg = rf.readAll();
ui->textEdit->setText(msg);
rf.close();
}
}
void Widget::on_savebtn_clicked()
{
QString fname = QFileDialog::getSaveFileName(this,"保存","./","Text File(*.txt);;Image File(*.jpg *.png *.bmp);;All File(*.*)");
if(fname.isNull())
{
QMessageBox::information(this,"文件选择","取消选择");
}
else
{
QFile wf(fname);
if(!wf.open(QFile::WriteOnly))
{
return;
}
QString buf;
buf = ui->textEdit->toPlainText();
qDebug() << buf;
wf.write(buf.toUtf8());
}
}
2.使用键盘事件实现图片的上下左右移动
cpp
-------------------------------------------------------------------------
widget.cpp
-------------------------------------------------------------------------
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
//键盘按下事件处理函数
void Widget::keyPressEvent(QKeyEvent *event)
{
qDebug() << "键盘按下" << event->text() << "键值为 : " << event->key();
switch(event->key())
{
case 'W':
ui->label->move(ui->label->x(),ui->label->y()-1);
if(ui->label->y() <= 0-ui->label->height())
{
ui->label->move(ui->label->x(),this->height());
}
break;
case 'S':
ui->label->move(ui->label->x(),ui->label->y()+1);
if(ui->label->y() >= this->height())
{
ui->label->move(ui->label->x(),0-ui->label->height());
}
break;
case 'A':
ui->label->move(ui->label->x()-1,ui->label->y());
if(ui->label->x() <= 0-ui->label->width())
{
ui->label->move(this->width(),ui->label->y());
}
break;
case 'D':
ui->label->move(ui->label->x()+1,ui->label->y());
if(ui->label->x() >= this->width())
{
ui->label->move(0-ui->label->width(),ui->label->y());
}
}
}