最近用PyQT写个窗体工具,用到QFileDialog处理文件时程序就崩掉了,网上查的降版本,换32位解释器都尝试了都不靠谱,后面无意中看到一段示例代码终于解决了,记录一下,在给掉坑里的小伙伴做个参考。
原代码是用 qt 模板生成的,添加的构造方法:
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import QWidget
import os
import time
class Ui_MainWindow(Object):
def __init__(self):
self.zh_CN = {}
self.en_US = {}
self.cwd = os.getcwd()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(0, 0, 791, 551))
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.lineEdit = QtWidgets.QLineEdit(self.tab)
self.lineEdit.setGeometry(QtCore.QRect(30, 40, 541, 31))
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(self.tab)
self.pushButton.setGeometry(QtCore.QRect(620, 40, 91, 31))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.openFolder)
self.tabWidget.addTab(self.tab, "")
def openFolder(self):
dir_choose = QFileDialog.getExistingDirectory(self,"选取文件夹",self.cwd)
self.lineEdit.setText(str(dir_choose))
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
...
修改后代码:
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import QWidget
import os
import time
class Ui_MainWindow(QWidget):
def __init__(self):
super(Ui_MainWindow, self).__init__()
self.zh_CN = {}
self.en_US = {}
self.cwd = os.getcwd()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(0, 0, 791, 551))
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.lineEdit = QtWidgets.QLineEdit(self.tab)
self.lineEdit.setGeometry(QtCore.QRect(30, 40, 541, 31))
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(self.tab)
self.pushButton.setGeometry(QtCore.QRect(620, 40, 91, 31))
self.pushButton.setObjectName("pushButton_4")
self.pushButton.clicked.connect(self.openFolder)
self.tabWidget.addTab(self.tab, "")
def openFolder(self):
dir_choose = QFileDialog.getExistingDirectory(self,"选取文件夹",self.cwd)
self.lineEdit.setText(str(dir_choose))
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
标签:setObjectName,操作程序,self,PyQT5,QtWidgets,QFileDialog,tab,import,MainWindow
From: https://www.cnblogs.com/cnxue/p/17309606.html