qt项目总结
绘制圆弧 文字组合仪表盘void paintEvent(QPaintEvent* event){ Q_UNUSED(event); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); // 1. 绘制背景圆弧 painter.save(); painter.setPen(QPen(QColor(255, 255, 255), 4)); painter.drawArc(rect(), 30 * 16, 120 * 16); // 参数矩形, 起始角度(×16), 跨度(×16) painter.restore(); // 2. 绘制前景圆弧进度 painter.save(); painter.setPen(QPen(QColor(209, 107, 93), 4)); int spanAngle (int)(m_ratio * 120 * 16); // 根据比例计算跨度 painter.drawArc(rect(), 30 * 16, spanAngle); painter.restore(); // 3. 绘制文字 painter.save(); QFont font; font.setFamily(PingFang TC); font.setPixelSize(35); painter.setFont(font); painter.setPen(QColor(255, 255, 255)); painter.drawText(rect(), Qt::AlignCenter, 文字内容); painter.restore(); }子控件管理组合// .h 文件 private: RulerHead *m_pRUlerHead; QPoint m_originalPosition; // 记录初始位置 // .cpp 构造函数 CCRuler::CCRuler(QWidget *parent) : QWidget{parent}{ // 设置自身位置和大小 setGeometry(RULLERWIDGET_STARTX, RULLERWIDGET_STARTY, RULLERWIDGET_WIDTH, RULLERWIDGET_HIGHET); setAutoFillBackground(true); setStyleSheet(background-color:rgba(0,0,0,0)); // 创建子控件 m_pRUlerHead new RulerHead(this); // 记录子控件初始位置 m_originalPosition m_pRUlerHead-pos(); // 连接信号 connect(m_pRUlerHead, RulerHead::rulerHeadMoveSignal, this, CCRuler::OnRulerHeadMove); connect(m_pRUlerHead, RulerHead::rulerHeadMoveDoneSignal, this, CCRuler::OnrulerHeadMoveDone); } // 析构函数 CCRuler::~CCRuler(){ if(m_pRUlerHead ! NULL){ delete m_pRUlerHead; m_pRUlerHead nullptr; } } // 限制子控件移动范围 void CCRuler::OnRulerHeadMove(int aValue){ int realPosY aValue; if(realPosY RULLER_MAX_HEIGHET realPosY 0){ m_pRUlerHead-move(m_originalPosition.rx(), realPosY); } }多层绘制组合save/restorevoid paintEvent(QPaintEvent* event){ Q_UNUSED(event); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); // 第一层绘制背景 painter.save(); painter.drawPixmap(rect(), QPixmap(:/images/background.png)); painter.restore(); // 第二层绘制进度条 painter.save(); painter.setPen(QPen(QColor(127, 159, 124), 1)); painter.setBrush(QColor(127, 159, 124)); painter.drawRect(15, 3, 52, currentHeight); painter.restore(); // 第三层绘制刻度 painter.save(); painter.setPen(QPen(QColor(255, 255, 255), 1)); // 绘制刻度线... painter.restore(); // 第四层绘制文字 painter.save(); painter.setFont(font); painter.setPen(QColor(255, 255, 255)); painter.drawText(rect(), Qt::AlignCenter, text); painter.restore(); }图片旋转绘制指针/仪表盘void paintEvent(QPaintEvent* event){ // 绘制底图 painter.save(); painter.drawPixmap(rect(), QPixmap(:/images/dial.png)); painter.restore(); // 绘制旋转的指针 painter.save(); painter.translate(width()/2, height()/2); // 移动到中心点 painter.rotate(m_rotateValue); // 旋转 // 绘制图片注意坐标是相对于中心点的 painter.drawPixmap(-13, -78, 26, 90, QPixmap(:/images/needle.png)); painter.restore(); }自定义绘制背景图片// .h 文件 protected: void paintEvent(QPaintEvent* event); // .cpp 文件 void MainWindow::paintEvent(QPaintEvent* event){ Q_UNUSED(event); // 避免编译器警告 QPainter painter(this); painter.save(); // 保存状态 painter.drawPixmap(rect(), QPixmap(:/images/path/to/background.png)); painter.restore(); // 恢复状态 }窗口居中固定大小// 在构造函数中使用 #define WINDOW_WIDTH 436 #define WINDOW_HEIGHT 775 // 获取主屏幕并居中 QScreen *screen QGuiApplication::primaryScreen(); QRect screenGeometry screen-geometry(); int startX (screenGeometry.width() - WINDOW_WIDTH) / 2; int startY (screenGeometry.height() - WINDOW_HEIGHT) / 2; setGeometry(startX, startY, WINDOW_WIDTH, WINDOW_HEIGHT); // 固定窗口大小 setMinimumSize(WINDOW_WIDTH, WINDOW_HEIGHT); setMaximumSize(WINDOW_WIDTH, WINDOW_HEIGHT); // 禁用最大化最小化按钮 setWindowFlags(windowFlags() ~Qt::WindowMinMaxButtonsHint); ## 长按检测 **功能** 检测用户长按操作常用于手机端交互 cpp // 头文件 class LongPressButton : public QPushButton { Q_OBJECT public: explicit LongPressButton(QWidget* parent nullptr) : QPushButton(parent) { m_pTimer new QTimer(this); m_pTimer-setSingleShot(true); m_pTimer-setInterval(500); // 长按阈值 500ms connect(m_pTimer, QTimer::timeout, this, LongPressButton::OnLongPress); } protected: void mousePressEvent(QMouseEvent* event) override { if(event-button() Qt::LeftButton) { m_pTimer-start(); } QPushButton::mousePressEvent(event); } void mouseReleaseEvent(QMouseEvent* event) override { m_pTimer-stop(); QPushButton::mouseReleaseEvent(event); } void mouseMoveEvent(QMouseEvent* event) override { if(!rect().contains(event-pos())) { m_pTimer-stop(); } QPushButton::mouseMoveEvent(event); } private slots: void OnLongPress() { emit longPressSignal(); } signals: void longPressSignal(); private: QTimer* m_pTimer; };震动/摇摆动画功能让控件产生左右摇摆的动画效果// 头文件 class ShakeWidget : public QWidget { Q_OBJECT public: void StartShake(QWidget* targetWidget) { if(m_pAnimation nullptr) { m_pAnimation new QPropertyAnimation(targetWidget, pos); m_pAnimation-setDuration(100); m_pAnimation-setLoopCount(-1); // 无限循环 } QPoint startPos targetWidget-pos(); m_pAnimation-setKeyValueAt(0, startPos); m_pAnimation-setKeyValueAt(0.25, startPos QPoint(3, 0)); m_pAnimation-setKeyValueAt(0.5, startPos); m_pAnimation-setKeyValueAt(0.75, startPos QPoint(-3, 0)); m_pAnimation-setKeyValueAt(1.0, startPos); m_pAnimation-start(); } void StopShake() { if(m_pAnimation) m_pAnimation-stop(); } private: QPropertyAnimation* m_pAnimation nullptr; };页面滑动切换跟手效果功能实现类似手机浏览器的页面滑动切换// 核心思路手动计算位置 双缓冲显示 void StackedWidget::UpdateSlide(float distance) { QWidget* current m_list[currentIndex]; QWidget* next m_list[nextIndex]; next-setHidden(false); if(distance 0) { // 左滑 current-move(distance, 0); next-move(width() - qAbs(distance), 0); } else { // 右滑 current-move(distance, 0); next-move(-width() distance, 0); } } void StackedWidget::FinishSlide() { currentIndex nextIndex; // 隐藏其他显示当前 for(int i 0; i list.count(); i) { list[i]-setHidden(i ! currentIndex); list[i]-move(0, 0); // 复位 } }批量操作多个同类控件功能统一控制列表中的所有控件void MyWidget::showAll() { for(int i 0; i m_widgetList.count(); i) { if(m_widgetList[i]) { m_widgetList[i]-setVisible(true); } } } void MyWidget::hideAll() { for(int i 0; i m_widgetList.count(); i) { if(m_widgetList[i]) { m_widgetList[i]-setVisible(false); } } } void MyWidget::operateAll(std::functionvoid(QWidget*) operation) { for(int i 0; i m_widgetList.count(); i) { if(m_widgetList[i]) { operation(m_widgetList[i]); } } }拖放文件到窗口功能支持拖拽文件到窗口获取文件路径// 1. 启用拖放 setAcceptDrops(true); // 2. 拖入事件 void MyWidget::dragEnterEvent(QDragEnterEvent* event) { if(event-mimeData()-hasUrls()) { event-acceptProposedAction(); } } // 3. 放下事件 void MyWidget::dropEvent(QDropEvent* event) { const QMimeData* mimeData event-mimeData(); if(mimeData-hasUrls()) { QListQUrl urlList mimeData-urls(); for(const QUrl url : urlList) { QString filePath url.toLocalFile(); // 处理文件... } } }点击空白区域检测功能检测鼠标点击是否在控件外部void MyWidget::mousePressEvent(QMouseEvent* event) { if(event-button() Qt::LeftButton) { // 检测是否点击在子控件上 bool clickedOnChild false; for(QWidget* child : findChildrenQWidget*()) { if(child-rect().contains(child-mapFromParent(event-pos()))) { clickedOnChild true; break; } } if(!clickedOnChild) { // 点击空白区域的处理 onBlankAreaClicked(); } } QWidget::mousePressEvent(event); }网格布局计算功能将控件排列成网格如 4列 x 多行void GridContainer::refreshLayout(int columns) { for(int i 0; i itemList.count(); i) { int col i % columns; int row i / columns; int x marginLeft col * (itemWidth spacing); int y marginTop row * (itemHeight spacing); itemList[i]-setGeometry(x, y, itemWidth, itemHeight); } }父子控件层级管理功能组合控件父控件包含多个子控件// 组合模式Container 包含多个子控件 class CardWidget : public QWidget { public: CardWidget(QWidget* parent) : QWidget(parent) { // 创建子控件 m_pIcon new QLabel(this); m_pTitle new QLabel(this); m_pButton new QPushButton(this); // 设置父控件属性 setFixedSize(80, 100); setStyleSheet(background: transparent;); } void setContent(const QString iconPath, const QString title) { m_pIcon-setPixmap(QPixmap(iconPath)); m_pTitle-setText(title); } private: QLabel* m_pIcon; QLabel* m_pTitle; QPushButton* m_pButton; };状态切换模式功能根据状态执行不同操作如正常模式 vs 编辑模式class ModeManager { public: enum Mode { ViewMode, EditMode }; void setMode(Mode mode) { m_currentMode mode; switch(mode) { case ViewMode: showAllDeleteButtons(false); break; case EditMode: showAllDeleteButtons(true); startAllAnimations(); break; } } bool isEditMode() const { return m_currentMode EditMode; } private: Mode m_currentMode ViewMode; };多层信号传递功能子控件 → 父控件 → 顶层控件的信号传递// Level 1: 底层控件发出信号 connect(childWidget, ChildWidget::someSignal, this, ParentWidget::onChildSignal); // Level 2: 父控件转发信号 connect(this, ParentWidget::onChildSignal, topWidget, TopWidget::onChildSignalFromParent);最基础的 Qt 编程套路总结使用icon画控件1. 基本用法最常用// 创建 QIcon QIcon icon(:/need/Resources/pauseButton.png); // 设置到按钮 QPushButton *button new QPushButton(); button-setIcon(icon); // 设置图标大小重要 button-setIconSize(QSize(60, 60)); // 设置按钮大小要匹配图标大小 button-setFixedSize(60, 60);2. QIcon 的核心优势特性说明保持原始比例图片不会被压缩变形自动适配支持不同尺寸的图片状态管理可以设置 normal、hover、pressed 等状态的图片透明支持自动处理透明通道3. QIcon 的套路标准流程// 第一步创建 QIcon QIcon icon(:/path/to/image.png); // 第二步设置图标大小关键 button-setIconSize(QSize(width, height)); // 第三步设置按钮大小匹配图标 button-setFixedSize(width, height); // 第四步设置样式表去掉默认样式 button-setStyleSheet( QPushButton { border: none; // 去掉边框 background: transparent; // 透明背景 } );4. 高级用法多状态图标// 创建 QIcon 并设置不同状态的图片 QIcon icon; // 正常状态 icon.addPixmap(QPixmap(:/normal.png), QIcon::Normal); // 悬停状态 icon.addPixmap(QPixmap(:/hover.png), QIcon::Active); // 按下状态 icon.addPixmap(QPixmap(:/pressed.png), QIcon::Selected); // 禁用状态 icon.addPixmap(QPixmap(:/disabled.png), QIcon::Disabled); // 设置到按钮 button-setIcon(icon);5. QIcon 的状态模式状态枚举值说明NormalQIcon::Normal默认状态ActiveQIcon::Active悬停状态SelectedQIcon::Selected选中/按下状态DisabledQIcon::Disabled禁用状态6. 常见问题与解决问题 1图标显示很小// ❌ 错误没有设置图标大小 button-setIcon(icon); // ✅ 正确设置图标大小 button-setIcon(icon); button-setIconSize(QSize(60, 60)); // 关键问题 2图标被压缩变形// ❌ 错误按钮大小和图标大小不匹配 button-setIcon(icon); button-setIconSize(QSize(60, 60)); button-setFixedSize(100, 30); // 不匹配 // ✅ 正确大小一致 button-setIcon(icon); button-setIconSize(QSize(60, 60)); button-setFixedSize(60, 60); // 匹配问题 3图标有默认边框// ❌ 错误没有设置样式表 button-setIcon(icon); // ✅ 正确去掉默认样式 button-setIcon(icon); button-setStyleSheet( QPushButton { border: none; background: transparent; } );7. 完整示例推荐写法// 创建按钮 QPushButton *button new QPushButton(parent); // 创建图标 QIcon icon(:/need/Resources/pauseButton.png); // 设置图标和大小 button-setIcon(icon); button-setIconSize(QSize(60, 60)); button-setFixedSize(60, 60); // 设置位置 button-move(160, 600); // 设置样式表简洁的点击效果 button-setStyleSheet( QPushButton { border: none; background: transparent; } QPushButton:hover { opacity: 0.8; } QPushButton:pressed { opacity: 0.6; } ); // 连接信号 connect(button, QPushButton::clicked, this, MyClass::onButtonClicked);8. QIcon vs background-image 对比特性QIconbackground-image图片比例保持原始按按钮大小缩放状态管理支持多状态需要样式表切换透明度自动处理需要手动设置推荐场景图标按钮背景装饰9. 总结QIcon 的核心套路创建 QIconQIcon icon(:/path/to/image.png);设置图标大小button-setIconSize(QSize(w, h));关键设置按钮大小button-setFixedSize(w, h);匹配图标去掉默认样式button-setStyleSheet(border: none; background: transparent;);添加点击效果使用opacity实现简洁的反馈记住setIconSize是最重要的不设置的话图标会显示得很小添加背景颜色进行调试void ccanstackedwidget::CreatePageWidgetWithCount(int count){ if(count 0){return;} for(int i0;icount; i){ CCFrameWidget* frameWidget new CCFrameWidget(this); frameWidget-setGeometry(0,0,STACKWIDGET_WIDTH,STACKWIDGET_HEIGHT); // frameWidget-setAutoFillBackground(true); // QPalette palette(frameWidget-palette()); // if(i 0) palette.setColor(QPalette::Window,Qt::blue); // if(i 1) palette.setColor(QPalette::Window,Qt::green); // if(i 2) palette.setColor(QPalette::Window,Qt::red); // frameWidget-setPalette(palette); connect(frameWidget, SIGNAL(mouseMoveDistanceOnStackFrame(QPoint)), SLOT(OnmouseMoveDistanceOnStackFrame(QPoint))); connect(frameWidget, SIGNAL(mouseReleaseOnStackFrame()), SLOT(OnmouseReleaseOnStackFrame())); if(i 0){ frameWidget-setHidden(false);} else{ frameWidget-setHidden(true); } m_stackFramelist.append(frameWidget); } }按钮创建与布局// 创建按钮 QPushButton* btn new QPushButton(点击我, this); btn-setGeometry(100, 100, 100, 30); // 或者用布局 QVBoxLayout* layout new QVBoxLayout(this); layout-addWidget(btn);信号槽连接// 方式1Qt5 新语法推荐 connect(btn, QPushButton::clicked, this, MyWidget::onBtnClicked); // 方式2旧语法 connect(btn, SIGNAL(clicked()), SLOT(onBtnClicked())); // 方式3Lambda 表达式适用于简单逻辑 connect(btn, QPushButton::clicked, [](){ qDebug() 按钮被点击; });Label 使用// 创建文本标签 QLabel* label new QLabel(Hello, this); label-setGeometry(10, 10, 100, 30); // 创建图片标签 QLabel* imageLabel new QLabel(this); imageLabel-setPixmap(QPixmap(:/pic/image.png));获取控件并设置属性// 在 UI 类中ui 是 ui_mainwindow.h 生成的 ui-label-setText(新文本); ui-btn-setEnabled(true); ui-label-setStyleSheet(color: red;);添加资源图片// 方式1Qt 资源系统推荐 label-setPixmap(QPixmap(:/pic/folder/image.png)); // 方式2本地文件路径 label-setPixmap(QPixmap(D:/project/images/image.png));定时器使用// 创建定时器 QTimer* timer new QTimer(this); timer-setInterval(1000); // 1秒 // 连接信号 connect(timer, QTimer::timeout, this, MyWidget::onTimer); // 启动/停止 timer-start(); // timer-stop();窗口属性设置// 无边框窗口 setWindowFlags(Qt::FramelessWindowHint); // 置顶窗口 setWindowFlags(Qt::WindowStaysOnTopHint); // 透明背景 setAttribute(Qt::WA_TranslucentBackground); // 固定大小 setFixedSize(400, 300);样式表 QSS// 设置背景色 setStyleSheet(background-color: red;); // 设置按钮样式 btn-setStyleSheet(QPushButton { background-color: #3498db; color: white; border-radius: 5px; padding: 5px; } QPushButton:hover { background-color: #2980b9; });布局管理器// 垂直布局 QVBoxLayout* vLayout new QVBoxLayout(); vLayout-addWidget(widget1); vLayout-addWidget(widget2); setLayout(vLayout); // 水平布局 QHBoxLayout* hLayout new QHBoxLayout(); // 网格布局 QGridLayout* gridLayout new QGridLayout(); gridLayout-addWidget(widget, row, col); // 弹簧 vLayout-addStretch(); // 添加弹簧 vLayout-addSpacing(10); // 添加间距获取父控件// 获取父控件 QWidget* parent this-parentWidget(); // 转换类型 MyWidget* myParent qobject_castMyWidget*(this-parent());套路 设置控件位置widget-setGeometry(x, y, width, height); widget-move(x, y); widget-resize(width, height); widget-setFixedSize(width, height);字符串处理QString str Hello; // 拼接 QString full str World; QString full2 QString(%1 %2).arg(str).arg(World); // 转换 int num str.toInt(); QString numStr QString::number(123); // 判断 if(str.contains(ell)) { } if(str.startsWith(Hel)) { }列表遍历QListQString list; list a b c; // 方式1for 循环 for(int i 0; i list.count(); i) { qDebug() list[i]; } // 方式2foreach foreach(QString item, list) { qDebug() item; } // 方式3迭代器 for(auto it list.begin(); it ! list.end(); it) { qDebug() *it; }窗口标题和图标setWindowTitle(我的窗口); setWindowIcon(QIcon(:/pic/icon.png));鼠标光标设置setCursor(Qt::PointingHandCursor); // 手型 setCursor(Qt::ArrowCursor); // 箭头 setCursor(Qt::WaitCursor); // 等待窗口层级widget-raise(); // 移到最上层 widget-lower(); // 移到最下层
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2433448.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!