参数 1 的类型意外为 'Ui_mainWindow
我正在为我写的一个小程序制作一个图形用户界面(GUI),这个程序得到了这里一些人的帮助。总之,我用PyQt做了这个界面,看起来还不错。我添加了一个按钮,叫做dirButton,上面写着“选择目录”。
self.dirButton = QtGui.QPushButton(self.buttonWidget)
self.dirButton.setGeometry(QtCore.QRect(0, 0, 91, 61))
self.dirButton.setObjectName(_fromUtf8("dirButton"))
self.dirButton.clicked.connect(self.browse)
在底部的代码中,我让这个按钮在被点击时调用self.browse,代码是:
def browse(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '.')
fname = open(filename)
data = fname.read()
self.textEdit.setText(data)
fname.close()
但是,我遇到了这个错误:
Traceback (most recent call last):
File "C:\Users\Kevin\Desktop\python-tumblr-0.1\antearaGUI.py", line 88, in browse
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '.')
TypeError: QFileDialog.getOpenFileName(QWidget parent=None, QString caption=QString(), QString directory=QString(), QString filter=QString(), QString selectedFilter=None, QFileDialog.Options options=0): argument 1 has unexpected type 'Ui_mainWindow'
ui_mainWindow是一个类,里面存储了我所有的GUI按钮和整个界面。
class Ui_mainWindow(object):
我不明白为什么会出现这个错误,有人能给我点建议吗?
这是整个GUI的pastebin链接: http://pastebin.com/BWCcXxUW
4 个回答
def browseFiles(self):
text, placeholder = QFileDialog.getOpenFileName(None, 'Select file')
对我来说,解决这个问题的方法是使用 None
,而不是 self
。因为 self
会继承它上面的窗口类型,而这个类型应该是 None,但实际上却被当成 QMainWindow
了。
我还把它返回的元组拆开了,因为这个函数返回了两个可以使用的对象。
希望这对你有帮助,也许其他人能更好地解释为什么这样做有效。
总结:这个函数期望第一个参数是 None
,但由于 self
的原因,它却继承了一个 QMainWindow
类型。
导入以下内容:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui, QtCore
在类 Ui_MainWindow(object) 中,把 object 替换成 QWidget:
Ui_MainWindow(QWidget)
根据我的理解,你正在使用从 .ui
文件生成的 Ui_mainWindow
。如你所见,Ui_mainWindow
其实就是一个包含各种控件的 Python 类。getOpenFileName
方法的第一个参数需要传入一个 QWidget
实例。所以你需要创建一个 QWidget
或 QMainWindow
的子类,并在这个类里定义一些方法。
代码大概是这样的:
import sys
from PyQt4 import QtCore, QtGui
from file_with_ui import Ui_MainWindow
class Main(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setupUi(self)
def browse(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '.')
fname = open(filename)
data = fname.read()
self.textEdit.setText(data)
fname.close()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
另外,你也可以把 ui
存储为实例属性:
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
这样你就可以通过 self.ui
来访问你的控件,比如:self.ui.textEdit.setText(data)
建议你看看关于 pyuic
使用的教程,链接在这里:PyQt 示例(第一节)