背景
近段時(shí)間使用python+pyqt5做了一個(gè)占用應(yīng)用,現(xiàn)總結(jié)下實(shí)現(xiàn)過程中的一些經(jīng)驗(yàn)
環(huán)境搭建
網(wǎng)上針對(duì)pycharm+qt的環(huán)境搭建的教程很多弃秆,像這篇
安裝pyqt5关面、pyqt5-tools蜕青;
安裝pycharm
-
配置QtDesigner——通過Qt語言進(jìn)行UI設(shè)計(jì)(支持拖拽式的UI設(shè)計(jì))
image.png -
配置PyUIC——主要用來將QtDesigner代碼轉(zhuǎn)化成Python代碼
image.png -
配置Pyrcc—— 將圖片瘟栖、數(shù)據(jù)文件資源打包成py文件
image.png
經(jīng)驗(yàn)
-
支持高分辨率
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
-
添加窗口圖標(biāo)方法
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的添加資源方式添加,會(huì)自動(dòng)在.ui中生成對(duì)應(yīng)的代碼溉苛,通過Pyrcc命令之后就可以直接使用了
-
添加狀態(tài)欄镜廉,并在狀態(tài)欄中顯示時(shí)間
def __init__(self): ... ... self.statusbar = QtWidgets.QStatusBar() self.setStatusBar(self.statusbar) self.statusShowTime() def showCurrentTime(self, timeLabel): # 獲取系統(tǒng)當(dāng)前時(shí)間 time = QtCore.QDateTime.currentDateTime() # 設(shè)置系統(tǒng)時(shí)間的顯示格式 timeDisplay = time.toString('yyyy-MM-dd hh:mm:ss dddd') # print(timeDisplay) # 狀態(tài)欄顯示 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)) # 這個(gè)通過調(diào)用槽函數(shù)來刷新時(shí)間 self.timer.start(1000) # 每隔一秒刷新一次,這里設(shè)置為1000ms 即1s
-
tablewidget的標(biāo)題大小設(shè)置
# 第一個(gè)參數(shù)是標(biāo)題對(duì)應(yīng)的位置(從0開始)愚战,第二個(gè)參數(shù)是設(shè)置的寬度 self.tableWidget.horizontalHeader().resizeSection(0, 100)
tablewidget單元格一開始是None娇唯,只有在添加數(shù)據(jù)的時(shí)候創(chuàng)建QTableWidgetItem項(xiàng)添加到對(duì)應(yīng)單元格
-
QT Designer設(shè)計(jì)界面時(shí),子控件會(huì)繼承父控件的格式設(shè)置寂玲,如果不想要繼承塔插,則需要在父控件或者祖先控件的QSS中指定對(duì)應(yīng)的控件objname(可以同時(shí)指定多個(gè)),如下
只對(duì)tabwidget中每個(gè)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); }
參考博客
持續(xù)更新中断序。流纹。。