当前位置:   article > 正文

Qt 常用代码_qt代码

qt代码

Qt 常用代码

窗体居中并绘制背景

  1. #include <QDesktopWidget>
  2. #include <QApplication>
  3. setWindowFlags(windowFlags() & ~Qt::WindowMinMaxButtonsHint);
  4. setMinimumSize(LANCHERWIDGET_WIDTH ,LANCHERWIDGET_HEIGHT);
  5. setMaximumSize(LANCHERWIDGET_WIDTH ,LANCHERWIDGET_HEIGHT);
  6. setAutoFillBackground(true);
  7. setAttribute(Qt::WA_TranslucentBackground);
  8. QDesktopWidget *deskdop = QApplication::desktop();
  9. int startX = (deskdop->width() - LANCHERWIDGET_WIDTH)/2;
  10. int startY = (deskdop->height() - LANCHERWIDGET_HEIGHT)/2;
  11. setGeometry(startX, startY,LANCHERWIDGET_WIDTH,LANCHERWIDGET_HEIGHT);
  1. void XX::paintEvent(QPaintEvent* event)
  2. {
  3. Q_UNUSED(event);
  4. QPainter p(this);
  5. p.save();
  6. p.setRenderHint(QPainter::Antialiasing, true);
  7. p.drawPixmap(rect(),QPixmap(":/images/background.png"));
  8. p.restore();
  9. }

调色板使用

  1. setAutoFillBackground(true);
  2. QPalette palette;
  3. palette.setColor(QPalette::Background,Qt::green);
  4. setPalette(palette);

鼠标移动事件

  1. private:
  2. QPoint last_mouse_position;
  3. protected:
  4. void mousePressEvent(QMouseEvent* event);
  5. void mouseMoveEvent(QMouseEvent* event);
  6. void mouseReleaseEvent(QMouseEvent* event);
  1. void XX::mousePressEvent(QMouseEvent* event)
  2. {
  3. if (event->button() == Qt::LeftButton)
  4. {
  5. last_mouse_position = event->globalPos();
  6. }
  7. }
  8. void XX::mouseMoveEvent(QMouseEvent* event)
  9. {
  10. if (event->buttons() & Qt::LeftButton)
  11. {
  12. const QPoint position = event->globalPos() - last_mouse_position;
  13. //qDebug()<<"POSY:"<<last_mouse_position<<""<<event->globalPos()<<" "<< position;
  14. }
  15. }
  16. void XX::mouseReleaseEvent(QMouseEvent* event)
  17. {
  18. Q_UNUSED(event);
  19. //emit moveDoneSignal();
  20. }

QLabel实现点击事件

QT添加qss文件和资源文件

QT自定义控件(Widget+QSS)

关于子类化QWidget后使用QSS不能生效的问题

Qt自定义QWidget控件设置QSS

  • 或者在指定文件夹里自行创建 xxx.qss,然后用类似于引用图片的方式引入qss文件。
  • 自定义窗体设置样式
  • 构造函数中
setAttribute(Qt::WA_StyledBackground,true);
  • 重写paintEvent函数,注意设置抗锯齿,否则窗体设置圆角时有锯齿
  1. void XX::paintEvent(QPaintEvent *event)
  2. {
  3. Q_UNUSED(event);
  4. QStyleOption opt;
  5. opt.init(this);
  6. QPainter pt(this);
  7. pt.setRenderHint(QPainter::Antialiasing, true);
  8. style()->drawPrimitive(QStyle::PE_Widget, &opt, &pt, this);
  9. QWidget::paintEvent(event);
  10. // QPainter p(this);
  11. // p.save();
  12. // p.setRenderHint(QPainter::Antialiasing, true);
  13. // p.drawPixmap(rect(),QPixmap(":/img/loginbkg.png"));
  14. // p.restore();
  15. }

Qt控件的使用

添加阴影与圆角

Qt 给顶层窗口和子控件添加阴影和圆角

Qt 如何实现窗口的阴影效果

弹窗

Qt QMessageBox用法详解

Qt中QMessageBox的用法---看这一篇就够了

智能指针

Qt 之 智能指针汇总

设置样式格式

  1. //设置样式表
  2. QStringList list;
  3. list << "#titleBar{background:#BBBBBB;}";
  4. list << "#titleBar{border-top-left-radius:8px;border-top-right-radius:8px;}";
  5. list << "#widgetMain{border:2px solid #BBBBBB;background:#FFFFFF;}";
  6. //list << "#widgetMain{border-bottom-left-radius:8px;border-bottom-right-radius:8px;}";
  7. this->setStyleSheet(list.join(""));

设置背景图片自适应大小

  1. this->setObjectName("loginPage");
  2. this->setStyleSheet("QWidget#loginPage{border-image:url(:/core/images/app/login_background.png);}");
  1. QComboBox {
  2. border: 1px solid #aaaaaa;
  3. border-radius: 2px;
  4. padding: 1px 18px 1px 3px;
  5. font-family: "Source Han Sans CN Regular";
  6. font-size: 13px;
  7. height: 28px;
  8. }
  9. QComboBox:editable {
  10. background: white;
  11. }
  12. QComboBox QAbstractItemView::item {
  13. height: 28px; /* 项的高度(设置pComboBox->setView(new QListView(this));后,该项才起作用) */
  14. }
  15. /* 设置为可编辑editable时,点击下拉框的样式 */
  16. QComboBox::drop-down:editable:on {
  17. background: #dadada;
  18. }
  19. /* 设置为非编辑!editable时,下拉框的样式 */
  20. QComboBox::drop-down:!editable {
  21. background: #dadada;
  22. }
  23. /* 设置为非编辑!editable时,点击下拉框的样式 */
  24. QComboBox::drop-down:!editable:on {
  25. background: #dadada;
  26. }
  27. /* 点击QComboBox */
  28. QComboBox:on {
  29. }
  30. /* 下拉框样式 */
  31. QComboBox::drop-down {
  32. subcontrol-origin: padding; /* 子控件在父元素中的原点矩形。如果未指定此属性,则默认为padding。 */
  33. subcontrol-position: top right; /* 下拉框的位置(右上) */
  34. width: 15px; /* 下拉框的宽度 */
  35. border-left-width: 1px; /* 下拉框的左边界线宽度 */
  36. border-left-color: darkgray; /* 下拉框的左边界线颜色 */
  37. border-left-style: solid; /* 下拉框的左边界线为实线 */
  38. border-top-right-radius: 3px; /* 下拉框的右上边界线的圆角半径(应和整个QComboBox右上边界线的圆角半径一致) */
  39. border-bottom-right-radius: 3px; /* 同上 */
  40. }
  41.  /* 越过下拉框样式 */
  42.  QComboBox::drop-down:hover {
  43.    background: yellow;
  44.  }
  45. QComboBox::down-arrow {
  46. border-image: url(:/assets/imges/down_arrow.png);
  47.   width: 28px;
  48.   background: transparent;
  49.   padding: 5px 0px 5px 0px;
  50. }
  51. QComboBox::down-arrow:on {
  52.   border-image: url(:/assets/imges/down_up.png); /* 显示上拉箭头 */
  53. }
  • Button样式
  1. QPushButton[class=RouterBtnType1]{
  2. background: #FFFFFF;
  3. border-radius: 2px;
  4. /* border: 1px solid rgba(0,0,0,0.15);*/
  5. border: 1px solid #aaaaaa;
  6. font-family: "Source Han Sans CN Medium";
  7. font-size: 13px;
  8. height: 28px;
  9. color: #333333;
  10. }
  11. QPushButton[class=RouterBtnType1]:hover{
  12. border: 1px solid #4CACFD;
  13. color: #4CACFD;
  14. }
  15. QPushButton[class=RouterBtnType1]:pressed{
  16. background: #4CACFD;
  17. color: #FFFFFF;
  18. }
  19. QPushButton[class=RouterBtnType2]{
  20. background: #3f9dfd;
  21. border-radius: 4px;
  22. /* border: 1px solid rgba(0,0,0,0.15);*/
  23. border: none;
  24. height: 30px;
  25. font-size: 13px;
  26. font-family: "Source Han Sans CN Medium";
  27. color: #FFFFFF;
  28. }
  29. QPushButton[class=RouterBtnType2]:hover{
  30. background: #67b2ff;
  31. }
  32. QPushButton[class=RouterBtnType2]:pressed{
  33. background: #3a8de4;
  34. }
  35. QPushButton[class=RouterBtnType2]:disabled{
  36. background: #dadada;
  37. color: #aaaaaa;
  38. }
  • QLineEdit
  1. QLineEdit{
  2. border: 1px solid #aaaaaa;
  3. border-radius: 2px;
  4. font-family: "Source Han Sans CN Regular";
  5. font-size: 13px;
  6. /* width: 200px;*/
  7. height: 28px;
  8. }

  1. #ifndef COMMONHELPER_H
  2. #define COMMONHELPER_H
  3. #include <QFile>
  4. //#include <QApplication>
  5. #include <QWidget>
  6. #include <QPixmap>
  7. #include <QLabel>
  8. #include <QStyle>
  9. class CommonHelper
  10. {
  11. public:
  12. CommonHelper();
  13. public:
  14. static void setStyle(QWidget* wnd,const QString &style) {
  15. if(!wnd) return;
  16. QFile qss(style);
  17. qss.open(QFile::ReadOnly);
  18. wnd->setStyleSheet(qss.readAll());
  19. qss.close();
  20. }
  21. static void setLabelIcon(QLabel* lab, QString url, int size){
  22. if(!lab) return;
  23. QPixmap pixmap = QPixmap::fromImage(QImage(url));
  24. QPixmap fitpixmap = pixmap.scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
  25. lab->setScaledContents(true);
  26. lab->setPixmap(fitpixmap);
  27. }
  28. static void updateWidget(QWidget* w){
  29. if(!w) return;
  30. w->style()->unpolish(w);
  31. w->style()->polish(w);
  32. w->update();
  33. }
  34. };
  35. #endif // COMMONHELPER_H

设置滑动条

  1. //滑动条样式表
  2. QString scrollBarStyle = QString(
  3. "QScrollBar{background:transparent; width:10px; margin:0px 0px 0px 0px;}"
  4. "QScrollBar::handle{background:rgba(63, 64, 65, 200); border:0px; border-radius:5px; margin:0px 0px 0px 0px;}"
  5. "QScrollBar::handle:hover{background:lightgray;}"
  6. "QScrollBar::handle:pressed{background:rgba(200, 200, 200, 255);}"
  7. "QScrollBar::sub-page{background:transparent;}"
  8. "QScrollBar::add-page{background:transparent;}"
  9. "QScrollBar::up-arrow{background:transparent;}"
  10. "QScrollBar::down-arrow{background:transparent;}"
  11. "QScrollBar::sub-line{background:transparent;}"
  12. "QScrollBar::add-line{background:transparent;}"
  13. );
  14. //滑动条
  15. QScrollBar *scrollBar = new QScrollBar(m_listView);
  16. scrollBar->setStyleSheet(scrollBarStyle);
  17. m_listView->setVerticalScrollBar(scrollBar);
  18. m_listView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  1. QScrollBar{background:transparent; width:10px; margin:0px 0px 0px 0px;}
  2. QScrollBar::handle{background:rgba(63, 64, 65, 200); border:0px; border-radius:5px; margin:0px 0px 0px 0px;}
  3. QScrollBar::handle:hover{background:lightgray;}
  4. QScrollBar::handle:pressed{background:rgba(200, 200, 200, 255);}
  5. QScrollBar::sub-page{background:transparent;}
  6. QScrollBar::add-page{background:transparent;}
  7. QScrollBar::up-arrow{background:transparent;}
  8. QScrollBar::down-arrow{background:transparent;}
  9. QScrollBar::sub-line{background:transparent;}
  10. QScrollBar::add-line{background:transparent;}

添加滚动区域

  1. //主布局
  2. QVBoxLayout* vMainBox = new QVBoxLayout();
  3. vMainBox->addWidget(topContainer);
  4. vMainBox->addWidget(signalStatusWidget);
  5. vMainBox->addWidget(routerConfWidget);
  6. vMainBox->setMargin(0);
  7. vMainBox->setSpacing(SHADOW_WIDTH);
  8. vMainBox->setContentsMargins(SHADOW_WIDTH, SHADOW_WIDTH, SHADOW_WIDTH, SHADOW_WIDTH);
  9. QWidget * mainContainer = new QWidget(this);
  10. mainContainer->setObjectName("mainContainer");
  11. mainContainer->setLayout(vMainBox);
  12. QScrollArea *scrollArea = new QScrollArea(this);
  13. scrollArea->setWidgetResizable(true);
  14. scrollArea->setWidget(mainContainer);
  15. QHBoxLayout *hMainLayout = new QHBoxLayout;
  16. hMainLayout->addWidget(scrollArea);
  17. hMainLayout->setMargin(0);
  18. hMainLayout->setSpacing(0);
  19. hMainLayout->setContentsMargins(0, 0, 0, 0);
  20. this->setLayout(hMainLayout);

设置分隔区域

  1. QScrollArea *scrollArea = new QScrollArea(this);
  2. scrollArea->setObjectName("FancyTabScrollArea");
  3. scrollArea->setWidget(m_modesStackContainer);
  4. scrollArea->setWidgetResizable(true);
  5. m_vSplitter = new QSplitter(Qt::Vertical, this);
  6. m_vSplitter->addWidget(scrollArea);
  7. m_vSplitter->addWidget(m_statusWidget);
  8. m_vSplitter->setChildrenCollapsible(false);
  9. m_statusWidget->setMinimumHeight(CCSTATUSWIDGET_MIN_HEIGHT);
  10. m_vSplitter->setSizes(QList<int>{9999, 1});
  11. m_splitterList = m_vSplitter->sizes();

字体加载

  • 方式1:
  1. int loadedFontID = QFontDatabase::addApplicationFont(":/assets/fonts/SourceHanSansCN-Medium.ttf");
  2. QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(loadedFontID);
  3. if (!loadedFontFamilies.empty())
  4. {
  5. QString sansCNFamily = loadedFontFamilies.at(0);
  6. qDebug() << " sansCNFamily " << sansCNFamily;
  7. QFont defaultFont = app.font();
  8. defaultFont.setFamily(sansCNFamily);
  9. //设置字体大小格式为pixel,字体占用固定像素。相同像素的大小屏,不会发生字体遮挡现象
  10. defaultFont.setPixelSize(13);
  11. app.setFont(defaultFont);
  12. }
  • 方式2:
  1. void loadFonts()
  2. {
  3. const QString creatorPath = QCoreApplication::applicationDirPath();
  4. QString dir = creatorPath + QLatin1String("/../share/fonts");
  5. const QFileInfoList fonts = QDir(dir).entryInfoList(QStringList("*.ttf"), QDir::Files);
  6. for (const QFileInfo &fileInfo : fonts)
  7. {
  8. QFontDatabase::addApplicationFont(fileInfo.absoluteFilePath());
  9. qDebug() << "fileInfo.absoluteFilePath() " << fileInfo.absoluteFilePath();
  10. }
  11. }

字体与颜色设置

  1. QFont defaultFont = app.font();
  2. defaultFont.setFamily("Source Han Sans CN Regular");
  3. defaultFont.setPixelSize(13);
  4. app.setFont(defaultFont);
  5. QPalette defaultPalette = app.palette();
  6. defaultPalette.setColor(QPalette::WindowText, QColor(51,51,51));
  7. app.setPalette(defaultPalette);

添加阴影

  1. #include <QGraphicsDropShadowEffect>
  2. #define SHADOW_WIDTH 15
  3. void XXWidget::addShadow(QWidget *w)
  4. {
  5. //设置具体阴影
  6. QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(w);
  7. // 阴影偏移
  8. shadowEffect->setOffset(0, 0);
  9. // 阴影颜色;
  10. shadowEffect->setColor(QColor(200, 200, 200, 220));
  11. // 阴影半径;
  12. shadowEffect->setBlurRadius(SHADOW_WIDTH);
  13. // 给窗口设置上当前的阴影效果;
  14. w->setGraphicsEffect(shadowEffect);
  15. }
  16. topContainer 布局 vMainBox->setContentsMargins(15, 10, 15, 10);
  17. topContainer 颜色 #FFFFFF
  18. addShadow(topContainer);

QCheckBox样式

  1. QCheckBox {
  2. spacing: 5px;
  3. }
  4. QCheckBox::indicator {
  5. width: 18px;
  6. height: 18px;
  7. }
  8. QCheckBox::indicator:unchecked {
  9. image: url(:/assets/imges/checkbox_unchecked.png);
  10. }
  11. QCheckBox::indicator:checked {
  12. image: url(:/assets/imges/checkbox_checked.png);
  13. }

对话框去掉问号

  1. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  2. 固定窗口大小
  3. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);

网格布局

  1. #include <QGridLayout>
  2. QWidget* topWidget = new QWidget(this);
  3. QWidget* bottomWidget = new QWidget(this)
  4. QGridLayout* gridBox = new QGridLayout(t
  5. gridBox->addWidget(topWidget, 0, 0, 1, 5)
  6. gridBox->addWidget(bottomWidget, 5, 0, 1,
  7. gridBox->setMargin(0);
  8. int margin = 30;
  9. gridBox->setContentsMargins(margin, margi
  10. gridBox->setSpacing(20);
  11. this->setLayout(gridBox);

QGraphicsView画布拖动,缩放

  1. double scale_;
  2. QPointF startPos_;
  3. qreal scaleValue_;
  4. bool isMove_;
  5. void MyCanvasView::wheelEvent(QWheelEvent *event)
  6. {
  7. if (event->modifiers() == Qt::CTRL)
  8. {
  9. //按住ctrl键 可以放大缩小
  10. if((event->delta() > 0)&&(scale_ >= 50))//最大放大到原始的50倍
  11. {
  12. return;
  13. }
  14. else if((event->delta() < 0)&&(scale_ <= 0.01))//缩小到自适应大小之后就不继续缩小
  15. {
  16. return;//重置大小和位置,使之自适应控件窗口大小
  17. }
  18. else
  19. {
  20. // 当前放缩倍数;
  21. qreal scaleFactor = this->matrix().m11();
  22. scale_ = scaleFactor;
  23. int wheelDeltaValue = event->delta();
  24. // 向上滚动,放大;
  25. if (wheelDeltaValue > 0)
  26. {
  27. this->scale(1.2, 1.2);
  28. }
  29. else
  30. {
  31. // 向下滚动,缩小;
  32. this->scale(1.0 / 1.2, 1.0 / 1.2);
  33. }
  34. update();
  35. }
  36. return;
  37. }
  38. QGraphicsView::wheelEvent(event);
  39. }
  40. void MyCanvasView::mousePressEvent(QMouseEvent *event)
  41. {
  42. if(event->button()== Qt::LeftButton && event->modifiers() == Qt::CTRL)
  43. {
  44. startPos_ = event->pos();//鼠标左击时,获取当前鼠标在图片中的坐标,
  45. isMove_ = true; //标记鼠标左键被按下
  46. viewport()->setCursor(Qt::PointingHandCursor);
  47. return;
  48. }
  49. QGraphicsView::mousePressEvent(event);
  50. }
  51. void MyCanvasView::mouseMoveEvent(QMouseEvent *event)
  52. {
  53. if(isMove_ && event->modifiers() == Qt::CTRL )
  54. {
  55. auto hBar = horizontalScrollBar();
  56. auto vBar = verticalScrollBar();
  57. auto delta = event->pos() - startPos_;
  58. startPos_ = event->pos();
  59. hBar->setValue(hBar->value() - delta.x());
  60. vBar->setValue(vBar->value() - delta.y());
  61. return;
  62. }
  63. QGraphicsView::mouseMoveEvent(event);
  64. }
  65. void MyCanvasView::mouseReleaseEvent(QMouseEvent *event)
  66. {
  67. viewport()->setCursor(Qt::ArrowCursor);
  68. isMove_ = false;//标记鼠标左键已经抬起
  69. QGraphicsView::mouseReleaseEvent(event);
  70. }

设置程序图标

  • 其中 app.rc
IDI_ICON1               ICON    DISCARDABLE     "app.ico"
  • 然后在CMakeLists.txt文件中将rc文件追加到源文件中:
  1. if (WIN32)
  2. list(APPEND DIR_LIB_SRCS app.rc)
  3. endif()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/521466
推荐阅读
相关标签
  

闽ICP备14008679号