Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argument 1 has unexpected type 'Ui_mainWindow'

Tags:

python

pyqt

pyqt4

I'm trying to make a GUI for a small program I wrote with the help of some people from here, anyway, I made the GUI in PyQt and it looks fine. I added a button called dirButton that says "Choose Directory"

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)

and in the bottom line there I've made it call self.browse when I click it, which is:

def browse(self):
    filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '.')
    fname = open(filename)
    data = fname.read()
    self.textEdit.setText(data)
    fname.close()

However, this is the error I get:

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'

So, ui_mainWindow is the class that all of my GUI buttons and the GUI itself is stored in.

class Ui_mainWindow(object):

I don't understand why I'm getting an error, does anyone have any ideas?

Here is a pastebin link to the entire GUI: http://pastebin.com/BWCcXxUW

like image 688
Anteara Avatar asked Feb 17 '12 14:02

Anteara


1 Answers

As I understand, you are using Ui_mainWindow generated from .ui file. As you can see Ui_mainWindow is just python class which contains widgets. getOpenFileName recieves QWidget instance as first parameter. So you need to subclass QWidget or QMainWindow and define methods in that class.

Code will look like this:

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_())

Alternatively you can store ui as instance attribute:

class Main(QtGui.QMainWindow):
    def __init__(self):
         QtGui.QMainWindow.__init__(self)
         self.ui=Ui_MainWindow()
         self.ui.setupUi(self)

And acces your controls through self.ui, e.g.: self.ui.textEdit.setText(data)

Consider reading tutorial about pyuic usage PyQt by Example (Session 1)

like image 90
reclosedev Avatar answered Sep 17 '22 11:09

reclosedev