美文网首页
PyQT5相关经验

PyQT5相关经验

作者: itsenlin | 来源:发表于2022-07-21 00:41 被阅读0次

    背景

    近段时间使用python+pyqt5做了一个占用应用,现总结下实现过程中的一些经验

    环境搭建

    网上针对pycharm+qt的环境搭建的教程很多,像这篇

    • 安装pyqt5、pyqt5-tools;

    • 安装pycharm

    • 配置QtDesigner——通过Qt语言进行UI设计(支持拖拽式的UI设计)


      image.png
    • 配置PyUIC——主要用来将QtDesigner代码转化成Python代码


      image.png
    • 配置Pyrcc—— 将图片、数据文件资源打包成py文件


      image.png

    经验

    • 支持高分辨率

      QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
      
    • 添加窗口图标方法

      self.w = QWidget()
      icon = QtGui.QIcon()
      icon.addPixmap(QtGui.QPixmap("./login/title.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
      self.w.setWindowIcon(icon)
      
    • label中添加图片,并按比例缩放

      self.logoLb.setPixmap(QtGui.QPixmap("./login/1.png").scaled(self.logoLb.width(), self.logoLb.height(),
                                                                  QtCore.Qt.AspectRatioMode.KeepAspectRatio,
                                                                  QtCore.Qt.TransformationMode.SmoothTransformation))
      
    • 添加图片的另外一种方法,使用qt designer的添加资源方式添加,会自动在.ui中生成对应的代码,通过Pyrcc命令之后就可以直接使用了

    • 添加状态栏,并在状态栏中显示时间

      def __init__(self):
          ... ...
          self.statusbar = QtWidgets.QStatusBar()
          self.setStatusBar(self.statusbar)
          self.statusShowTime()
          
      def showCurrentTime(self, timeLabel):
          # 获取系统当前时间
          time = QtCore.QDateTime.currentDateTime()
          # 设置系统时间的显示格式
          timeDisplay = time.toString('yyyy-MM-dd hh:mm:ss dddd')
          # print(timeDisplay)
          # 状态栏显示
          timeLabel.setText(timeDisplay)
      
      def statusShowTime(self):
          self.timer = QtCore.QTimer()
          self.timeLabel = QtWidgets.QLabel()
          font = QtGui.QFont()
          font.setFamily("微软雅黑")
          font.setPointSize(14)
          font.setBold(True)
          self.timeLabel.setFont(font)
          self.timeLabel.setAttribute(QtCore.Qt.WA_TranslucentBackground)
          self.timeLabel.setStyleSheet('color: white;')
          self.statusbar.addPermanentWidget(self.timeLabel, 0)
          self.timer.timeout.connect(lambda: self.showCurrentTime(self.timeLabel))  # 这个通过调用槽函数来刷新时间
          self.timer.start(1000)  # 每隔一秒刷新一次,这里设置为1000ms  即1s
      
    • tablewidget的标题大小设置

      # 第一个参数是标题对应的位置(从0开始),第二个参数是设置的宽度
      self.tableWidget.horizontalHeader().resizeSection(0, 100)
      
    • tablewidget单元格一开始是None,只有在添加数据的时候创建QTableWidgetItem项添加到对应单元格

    • QT Designer设计界面时,子控件会继承父控件的格式设置,如果不想要继承,则需要在父控件或者祖先控件的QSS中指定对应的控件objname(可以同时指定多个),如下
      只对tabwidget中每个tab使用背景图,而tab下的子控件,像label、button等不使用背景图

      #tabWidget, #tab,#tab_2, #tab_3, #tab_4, #tab_5, #tab_6, #tab_7, #tab_8, #tab_9 {
          border-image: url(:/login/login.png);
      }
      

      参考博客

    持续更新中。。。

    相关文章

      网友评论

          本文标题:PyQT5相关经验

          本文链接:https://www.haomeiwen.com/subject/xxzpirtx.html