当前位置: 首页 > news >正文

QT GUI代码大全(MainWindow, QFile, QPainter, QGraphicsItem/Scene/View)

文章目录

  • 窗口设置
    • QMainWindow类
  • 按钮和菜单
    • QMenuBar类
    • QMenu类
    • QAction类
  • 文件交互
    • QFileDialog类
    • QFileInfo类
    • QFile类
    • QTextStream
  • 绘图
    • QPixmap类
    • QPainter类
    • QBrush类
    • QPen类
    • QPainterPath类
  • 游戏场景
    • QGraphicsItem类
    • QGraphicsScene类
    • QGraphicsView类

窗口设置

QMainWindow类

  • QMainWindow(QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags())

  • void setCentralWidget(QWidget *widget); //set the given widget to the main window’s central widget

  • void setFixedSize(int w, int h); //set the size of the widget

  • void setWindowIcon(QIcon(QString filepath));

按钮和菜单

QMenuBar类

  • QMenuBar *QMainWindow::menuBar() const
    返回MainWindow的menu bar
    //creates and returns an empty menu bar if the menu bar does not exist.

  • QMenuBar::addMenu(QMenu *menu)

  • QMenuBar::addMenu(const QString& title)

QMenu类

  • addAction(QAction *action)
  • addSeparator()

QAction类

可以看成是一个动作,连接到槽

  • QAction(const QString &text, QObject *parent = nullptr)

  • 设置快捷键

void QAction::setShortcuts(const QList<QKeySequence> &shortcuts)
  • ->setStatusTip(tr("Start a new game")); 设置说明
  • ->setEnabled(false) 设置按钮激活状态
  • connect(aboutAction, &QAction::triggered, this, &MainWindow::about);

文件交互

QFileDialog类

用于打开文件选择窗口

QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),                                       "/home",  //文件夹目录
tr("Images (*.png *.xpm *.jpg)"));

QFileInfo类

用于获取文件的相关信息,比如后缀名等等

QString extension = fileInfo.suffix().toLower();  // 获取小写的文件后缀名

QFile类

  • QFile(QString filename, QObject *parent*);
  • .setFileName(filePath);

QTextStream

文本流,用于读取数据
QTextStream::QTextStream(FILE *fileHandle, QIODevice::OpenMode openMode = QIODevice::ReadWrite)

QTextStream in(&file);
  • 逐行读取
while(!in.atEnd()){QString line = in.readLine(); // 读取一行... // 逐行处理}file.close();

绘图

QPixmap类

贴图,纹理

  • QPixmap::QPixmap(int width, int height)
    //注释:上面尚未fill with color

  • QPixmap::QPixmap(const QString &fileName, const char *format = nullptr, Qt::ImageConversionFlags flags = Qt::AutoColor)

  • void QPixmap::fill(const QColor &color = Qt::white)

QPainter类

  • QPainter(QPaintDevice *device)
    例如
//QPixmap bg(TILE_SIZE, TILE_SIZE);
QPainter p(&bg);
QPainter p(this);
  • setBrush(const QBrush)
  • setPen(QPen)
  • drawRect(int x, int y, int width, int height);
  • drawLine
  • drawPath(const QPainterPath &path) //current pen
  • void QPainter::drawPolygon(const QPolygonF &points, Qt::FillRule fillRule = Qt::OddEvenFill)

void QPainter::drawEllipse(const QRectF &rectangle)

  • save 保存当前painter状态

  • restore 恢复

  • setRenderHint(QPainter::RenderHint hint, bool on = true)
    设置绘画风格
    比如

painter->setRenderHint(QPainter::Antialiasing);
//带有边缘

void QPainter::fillRect(const QRectF]&rectangle, const QBrush&brush)
Fills the given rectangle with the brush specified.

Alternatively, you can specify a QColor instead of a QBrush; the QBrush constructor (taking a QColor argument) will automatically create a solid pattern brush.

相应有 fillPath等等

QBrush类

刷子,可以是纹理/颜色
style设置绘制的方式

QPen类

  pen.setStyle(Qt::DashDotLine);pen.setWidth(3);pen.setBrush(Qt::green);pen.setCapStyle(Qt::RoundCap);pen.setJoinStyle(Qt::RoundJoin);painter.setPen(pen)

QPainterPath类

  • addRect等等

  • clear

  • boundingRect

  • capacity vs length

  • connectPath(&path)

  • contains(QPoint/QRect/QPainterPath)

  • 对应的intersect(相交),而contain是包含(区域)

  • lineTo

  • cubicTo 画线

0 moveTo
Moves the current position to (x, y) and starts a new subpath, implicitly closing the previous path.

游戏场景

QGraphicsItem类

  • setPos(x, y);

  • setData(int key, const QVariant &value);
    使用:serData(GD_Type, GO_Food);

  • QRectF QGraphicsItem::boundingRect() const;
    自定义,原虚函数
    返回Item的边界
    例子:return QRectF(-TILE_SIZE, -TILE_SIZE, TILE_SIZE * 2, TILE_SIZE * 2 );

  • (pure virtual) void QGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    原虚函数,被QGraphicsView调用
    例子:

painter->save();
painter->setRenderHint(QPainter::Antialiasing);
painter->fillPath(shape(), Qt::red);
painter->restore();
  • (virtual) QPainterPath shape()const
    例子:
QPainterPath p;
p.addEllipse(QPointF(TILE_SIZE / 2, TILE_SIZE / 2), FOOD_RADIUS, FOOD_RADIUS);return p;
  • QPointF mapFromScene(const QPointF &point) const
    将Scene坐标系中的坐标映射到本Item坐标系中的点坐标

  • void QGraphicsItem::advance(int phase)
    phase = 0 预更新
    phase = 1 更新
    用于更新Item相关逻辑

void Snake::advance(int step)
{if (!step) {return;}if (tickCounter++ % speed != 0) {return;}if (moveDirection == NoMove) {return;}if (growing > 0) {QPointF tailPoint = head;tail << tailPoint;growing -= 1;} else {tail.removeFirst();tail << head;}switch (moveDirection) {case MoveLeft:moveLeft();break;case MoveRight:moveRight();break;case MoveUp:moveUp();break;case MoveDown:moveDown();break;}setPos(head);handleCollisions();
}
  • void QGraphicsItem::setPos(const QPointF &pos)
    Sets the position of the item to pos, which is in parent coordinates.

  • 碰撞检测

QList<QGraphicsItem*> QGraphicsItem::collidingItems(Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const

可用之前设置的data判断与哪个物体的碰撞

QGraphicsScene类

//用于图形存放

  • QGraphicsScene(QObject* parent = nullptr);
    构造函数可用:
    …scene(new QGraphicsScene(this));

  • setSceneRect(x, y, w, h);//设置scene的位置
    //使用实例:scene->setSceneRect(-100, -100, 200, 200);

  • void addItem(QGraphicsItem *item);
    void removeItem(QGraphicsItem *item);

  • void QObject::installEventFilter(QObject *filterObj);
    //设置事件过滤器, filterObj会拦截并处理this的实践
    例子: scene.installEventFilter(this);

  • (virtual)
    bool QObject::eventFilter(QObject *object, QEvent *event)
    实现拦截处理函数
    例子

if (event->type() == QEvent::KeyPress) {handleKeyPressed((QKeyEvent *)event); //自定义的按键处理函数return true;//返回已处理
} else {return QObject::eventFilter(object, event);//不处理}
  • connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance()));
    用于定时刷新界面

QGraphicsView类

  • QGraphicsView(scene, this);

  • void fitInView(QRect, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio);
    缩放视图矩阵并滚动滚动条,以确保场景矩形(rect)适应视口内

  • setBackgroundBrush(QBrush(QPixmap)); //设置背景

相关文章:

  • SSH免密登录
  • leetcode 525. 连续数组(优质解法)
  • 使用包、Crate 和模块管理项目(下)
  • 性能压力测试--确保企业数字化业务稳健运行
  • 前端:NPM的介绍和使用
  • 杰发科技AC7840——在Eclipse环境下使用Jlink调试
  • SSM整合实战(Spring、SpringMVC、MyBatis)
  • 大模型赋能“AI+电商”,景联文科技提供高质量电商场景数据
  • flowable工作流学习笔记
  • 针对这两个趋势,3.0全新新零售商业模式可以采取以下策略:
  • 【WeLink群消息机器人webhook介绍】
  • 将Abp默认事件总线改造为分布式事件总线
  • OpenSSL 3.2.0新增Argon2支持——防GPU暴力攻击
  • 【Linux】macOS下使用scp命令编写脚本上传文件至服务器
  • 字符函数和字符串函数(2)
  • 【React系列】如何构建React应用程序
  • 【附node操作实例】redis简明入门系列—字符串类型
  • 2019年如何成为全栈工程师?
  • css属性的继承、初识值、计算值、当前值、应用值
  • HTTP传输编码增加了传输量,只为解决这一个问题 | 实用 HTTP
  • iOS筛选菜单、分段选择器、导航栏、悬浮窗、转场动画、启动视频等源码
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • Map集合、散列表、红黑树介绍
  • Node.js 新计划:使用 V8 snapshot 将启动速度提升 8 倍
  • Node项目之评分系统(二)- 数据库设计
  • php面试题 汇集2
  • redis学习笔记(三):列表、集合、有序集合
  • Swoft 源码剖析 - 代码自动更新机制
  • 好的网址,关于.net 4.0 ,vs 2010
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 聊聊sentinel的DegradeSlot
  • 免费小说阅读小程序
  • 一道面试题引发的“血案”
  • 一份游戏开发学习路线
  • 一些关于Rust在2019年的思考
  • 新海诚画集[秒速5センチメートル:樱花抄·春]
  • 移动端高清、多屏适配方案
  • #pragma once与条件编译
  • (8)STL算法之替换
  • (AtCoder Beginner Contest 340) -- F - S = 1 -- 题解
  • (ctrl.obj) : error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MDd_DynamicDebug”不匹配值“
  • (k8s中)docker netty OOM问题记录
  • (Pytorch框架)神经网络输出维度调试,做出我们自己的网络来!!(详细教程~)
  • (SpringBoot)第二章:Spring创建和使用
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (zhuan) 一些RL的文献(及笔记)
  • (二)学习JVM —— 垃圾回收机制
  • (附源码)spring boot智能服药提醒app 毕业设计 102151
  • (附源码)springboot学生选课系统 毕业设计 612555
  • (亲测成功)在centos7.5上安装kvm,通过VNC远程连接并创建多台ubuntu虚拟机(ubuntu server版本)...
  • (三)elasticsearch 源码之启动流程分析
  • (图)IntelliTrace Tools 跟踪云端程序
  • (原創) 人會胖會瘦,都是自我要求的結果 (日記)
  • .net 8 发布了,试下微软最近强推的MAUI
  • .net core控制台应用程序初识