使用习惯
变量命名
使用元件时最好给每个元件单独加后缀
各个元件的基本使用
按钮
class Test_window(QtWidgets.QMainWindow,Test_UI.Ui_MainWindow):
def __init__(self,parent=None):
super(Test_window,self).__init__(parent)
self.setupUi(self)
self.pushButton_OpenFile.clicked.connect(self.button_test)
def button_test(self):
print(self.pushButton_OpenFile.isChecked())
Label
常用小功能
打开文件或文件夹
基本方法
1.单个文件打开
QFileDialog.getOpenFileName()
2.多个文件打开
QFileDialog.getOpenFileNames()
3.文件夹选取
QFileDialog.getExistingDirectory()
4.文件保存
QFileDialog.getSaveFileName()
示例:
from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import QMainWindow,QApplication
from PyQt5.QtWidgets import QFileDialog
import sys
import Test_UI
class Test_window(QtWidgets.QMainWindow,Test_UI.Ui_MainWindow):
def __init__(self,parent=None):
super(Test_window,self).__init__(parent)
self.setupUi(self)
self.pushButton_OpenFile.clicked.connect(self.msg)
def msg(self):
directory1 = QFileDialog.getExistingDirectory(self,
"选取文件夹",
"./") # 起始路径
print(directory1)
fileName1, filetype = QFileDialog.getOpenFileName(self,
"选取文件",
"./",
"All Files (*);;Text Files (*.txt)") # 设置文件扩展名过滤,注意用双分号间隔
print(fileName1, filetype)
files, ok1 = QFileDialog.getOpenFileNames(self,
"多文件选择",
"./",
"All Files (*);;Text Files (*.txt)")
print(files, ok1)
fileName2, ok2 = QFileDialog.getSaveFileName(self,
"文件保存",
"./",
"All Files (*);;Text Files (*.txt)")
if __name__ == '__main__':
app = QApplication(sys.argv)
mytest = Test_window()
mytest.show()
app.exec_()
打开文件且显示图片
导入关键头文件QtGui
from PyQt5 import QtWidgets,QtCore,QtGui
class Test_window(QtWidgets.QMainWindow,Test_UI.Ui_MainWindow):
def __init__(self,parent=None):
super(Test_window,self).__init__(parent)
self.setupUi(self)
self.pushButton_OpenFile.clicked.connect(self.openimage)
def openimage(self):
imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
jpg = QtGui.QPixmap(imgName).scaled(self.label_ShowImg.width(), self.label_ShowImg.height())
self.label_ShowImg.setPixmap(jpg)
插入背景图片qcc
创建一个.qrc文件
<!DOCTYPE RCC>
<RCC version="1.0">
<qresource prefix="/">
<file>images/logo.png</file>
</qresource>
</RCC>
然后使用PTQCC转换,就可以直接在QtDesigner里面使用这些图片