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

本文主要是介绍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)); //设置背景

这篇关于QT GUI代码大全(MainWindow, QFile, QPainter, QGraphicsItem/Scene/View)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/519619

相关文章

Qt QCustomPlot库简介(最新推荐)

《QtQCustomPlot库简介(最新推荐)》QCustomPlot是一款基于Qt的高性能C++绘图库,专为二维数据可视化设计,它具有轻量级、实时处理百万级数据和多图层支持等特点,适用于科学计算、... 目录核心特性概览核心组件解析1.绘图核心 (QCustomPlot类)2.数据容器 (QCPDataC

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

Qt如何实现文本编辑器光标高亮技术

《Qt如何实现文本编辑器光标高亮技术》这篇文章主要为大家详细介绍了Qt如何实现文本编辑器光标高亮技术,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录实现代码函数作用概述代码详解 + 注释使用 QTextEdit 的高亮技术(重点)总结用到的关键技术点应用场景举例示例优化建议

Qt 设置软件版本信息的实现

《Qt设置软件版本信息的实现》本文介绍了Qt项目中设置版本信息的三种常用方法,包括.pro文件和version.rc配置、CMakeLists.txt与version.h.in结合,具有一定的参考... 目录在运行程序期间设置版本信息可以参考VS在 QT 中设置软件版本信息的几种方法方法一:通过 .pro