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
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)
import the following:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui, QtCore
In class Ui_MainWindow(object), replace object with QWidget:
Ui_MainWindow(QWidget)
def browseFiles(self):
text, placeholder = QFileDialog.getOpenFileName(None, 'Select file')
The way it worked out for me is to use None, rather than self, as self inherits the type of the window above it, which is expected to be None, but is given QMainWindow as a type.
I also unpacked the tuple it returns, since this function returns two objects to work with.
I hope this helps, perhaps someone else could explain this better, as to why it works.
TLDR: The function expects None as the first parameter, but inherits a QmainWindow as type, due to self.
file = str(QFileDialog.getExistingDirectory(None, "Select Directory"))
Related
Before writing the Python code, I already made a ui file to made QT designer. The UI file has one Qlabel containing the values. To output an external value, I've tried, but I never could never make it. This is the My QtCode
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
form_class = uic.loadUiType("untitled.ui")[0]
class WindowClass(QMainWindow, form_class) :
def __init__(self) :
super().__init__()
self.setupUi(self)
self.InitUI()
def InitUI(self, name):
self.hello.setText("Hello. %s"%name)
if __name__ == "__main__" :
app = QApplication(sys.argv)
myWindow = WindowClass()
myWindow.show()
app.exec_()
I want to accept the name value in if__name__=="main_" and hand it over to the part that outputs the label of the Qt class. I am not that good at English.
I try to read dataframe from excel file and print it after button click.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from excel_reading import *
class MyWin(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.hello)
def hello(self):
data_input_from_file = QtWidgets.QFileDialog.getOpenFileName(self,'header','filename','Excel (*.xlsx *.xls)')
print(data_input_from_file)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = MyWin()
myapp.show()
sys.exit(app.exec_())
When I click button, I have such message:
Gtk-Message: 00:03:53.573: GtkDialog mapped without a transient parent. This is discouraged.
('', '')
How should I solve that problem?
I solved the problem:
def hello(self):
data_input_from_file = QtWidgets.QFileDialog.getOpenFileName(self, 'header', 'filename', 'Excel (*.xlsx *.xls)')
print(type(data_input_from_file))
print(data_input_from_file)
print(pd.read_excel(data_input_from_file[0]))
The Gtk warning is just what it is: a warning. You can ignore that. Qt tries to use the system native file dialogs whenever possible, which might result in some warnings in the consolle output.
Your issue is related to something else: there are rare cases for which PyQt functions don't return the same signature as reported in the official Qt (C++) documentation.
QFileDialog static methods is one of such cases, as QFileDialog.getOpenFileName() always returns a tuple: the selected file path and the selected file type filter. This is also clear from the output of your code (which I suppose is caused by cancelling the dialog):
('', '')
The first value is the selected file (in this case, none) and filter (again, none, as there was no selected file).
The solution is to assign two values for what the static returns:
filePath, filters = QtWidgets.QFileDialog.getOpenFileName(
self,'header','filename','Excel (*.xlsx *.xls)')
if filePath:
# do something
I want to design my QWizardPages in Qt Designer and I want to load them into my Python program with PySide2. Previously I have been using PyQt5 without any problems but making the switch to PySide2 seems harder then expected.
The problem I am facing is that when I am adding a QWizardPage to my QWizard , the page is indeed added to the Wizard, but also an other (empty) page is added. I'm not able to find what I'm doing wrong so I was wondering if someone can have a look.
I have tried to add the pages with both the functions addPage() and setPage(), but they give the same results. What I also noticed is that when I explicitely set the Title of the page with setTitle(), the empty (unwanted) page gets this title, but not the page I designed in Qt Designer.
import os
import sys
from PySide2.QtWidgets import QWizard, QWizardPage, QApplication
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader
from enum import Enum
class MyWizard(QWizard):
def __init__(self):
super().__init__()
self.setPage(PageNumbers.page_one.value, PageOne(self))
class PageOne(QWizardPage):
def __init__(self, parent):
super().__init__(parent)
ui_file = os.path.join(__file__, '..', 'pageOne.ui')
file = QFile(ui_file)
file.open(QFile.ReadOnly)
loader = QUiLoader()
loader.load(file, parent)
file.close()
self.setTitle("This is another test Title")
class PageNumbers(Enum):
page_one = 1
if __name__ == '__main__':
app = QApplication(sys.argv)
wizard = MyWizard()
wizard.show()
app.exec_()
What I would expect is to have just one QWizardPage showing up with directly the Finish button. Instead I get two QWizardPages as shown in this image:
Can someone tell me what's going on?
(I get the expected result using PyQt5 with the following code: https://pastebin.com/6W2sx9M1)
The developers of PyQt implement functions to be able to create classes based on the .ui that is not implemented in Qt by default (Qt/C++ uses the MOC to do this work), but in the case of PySide2-Qt for python it does not implement it, only has the QUiLoader class that allows to create a widget based on the .ui unlike PyQt that allows filling a class.
In conclusion there is no equivalent in PySide2 of the loadUi function so you can not implement the same logic. PySide2 is not PyQt5, there are own equivalences since they use the same base but they have implementations, limitations and advantages.
Going to the practical problem, considering that the .ui is next to the .py the solution is the following:
import os
import sys
from PySide2 import QtCore, QtWidgets, QtUiTools
from enum import Enum
class PageNumbers(Enum):
page_one = 0
class MyWizard(QtWidgets.QWizard):
def __init__(self):
super().__init__()
ui_file = os.path.join(os.path.dirname(os.path.abspath(__file__)) ,'PageOne.ui')
page_one = create_widget(ui_file, self)
self.setPage(PageNumbers.page_one.value, page_one)
def create_widget(filename, parent=None):
file = QtCore.QFile(filename)
if not file.open(QtCore.QFile.ReadOnly):
return
loader = QtUiTools.QUiLoader()
widget = loader.load(file, parent)
return widget
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
wizard = MyWizard()
wizard.show()
sys.exit(app.exec_())
Here is the error I am getting, which I am really confused about. My UI file which I am loading has this button name and it matches. But for some reason it doesn't seem to recognize and load it. I just tried converting this code over to PySide (it was originally PyQt). Am I doing something wrong in translating it?
Error: AttributeError: file line 25: 'swapRefGUI' object has no attribute 'swapRefBtn' #
from PySide import QtCore, QtGui, QtUiTools
import maya.cmds as cmds
class swapRefGUI(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
loader = QtUiTools.QUiLoader()
uifile = QtCore.QFile('C:\Scripts\swapRef.ui')
uifile.open(QtCore.QFile.ReadOnly)
ui = loader.load(uifile, parent)
uifile.close()
self.setFixedSize(400, 300)
self.swapRefBtn.clicked.connect(self.swapRefBtn_clicked)
self.closeBtn.clicked.connect(self.close)
def swapRefBtn_clicked(self):
pass
if __name__ == "__main__":
#app = QApplication(sys.argv)
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)
myGUI = swapRefGUI(None)
myGUI.show()
sys.exit(app.exec_())
Right now you are trying to access swapRefBtn through the class instance swapRefGUI, but you actually need to access it through the ui variable where you load. The 2nd argument of loader.load should also be self to display the qt gui in your window. There's also a few instances where you are trying to access objects from PySide like QDialog, when it should be QtGui.QDialog (because of the way you imported PySide module).
Here's some code that worked with a ui file.
from PySide import QtCore, QtGui, QtUiTools
import maya.cmds as cmds
class swapRefGUI(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
loader = QtUiTools.QUiLoader()
uifile = QtCore.QFile('C:\Scripts\swapRef.ui')
uifile.open(QtCore.QFile.ReadOnly)
self.ui = loader.load(uifile, self) # Qt objects are inside ui, so good idea to save the variable to the class, 2nd arg should refer to self
uifile.close()
self.setFixedSize(400, 300)
self.ui.swapRefBtn.clicked.connect(self.swapRefBtn_clicked) # Need to access button through self.ui
#self.ui.closeBtn.clicked.connect(self.close) # This needs to have an existing function in the class or it will crash when executing
def swapRefBtn_clicked(self):
print 'WORKS'
myGUI = swapRefGUI()
myGUI.show()
I am a bit of a novice so be kind ;-)
I had a GUI that I made using PyQt4 and python 2.6 with a working file dialog, (ie you clicked a button and a window popped up and allowed you to pick a file to load/save). The code for the GUI is like 2000 lines, so i will include the bits i think are important:
from PyQt4 import QtGui as qt
from PyQt4 import QtCore as qc
class NuclearMotion(qt.QWidget):
def __init__(self, parent=None):
super(NuclearMotion, self).__init__(parent)
file_button = qt.QPushButton("Use data from file")
mainLayout = qt.QGridLayout()
mainLayout.addWidget(file_button, 14, 8, 1, 2)
def choose_file():
file_name = qt.QFileDialog.getOpenFileName(self, "Open Data File", "", "CSV data files (*.csv)")
self.connect(file_button, qc.SIGNAL("clicked()"), choose_file)
self.setLayout(mainLayout)
if __name__ == '__main__':
import sys
app = qt.QApplication(sys.argv)
NuclearMotionWidget = NuclearMotion()
NuclearMotionWidget.show()
sys.exit(app.exec_())
The above works absolutely fine. I typed all the code for it manually using various tutorials. I have now made a new GUI using QT designer and pyuic4 to convert it to a .py file. Now I can't make the file dialog work. The below code results in a Type error:
from PyQt4 import QtCore, QtGui
class Ui_mainLayout(object):
def setupUi(self, mainLayout):
mainLayout.setObjectName(_fromUtf8("mainLayout"))
mainLayout.resize(598, 335)
mainLayout.setTabPosition(QtGui.QTabWidget.North)
mainLayout.setTabShape(QtGui.QTabWidget.Rounded)
mainLayout.setElideMode(QtCore.Qt.ElideLeft)
self.basic_tab = QtGui.QWidget()
self.file_button = QtGui.QPushButton(self.basic_tab)
QtCore.QObject.connect(self.file_button, QtCore.SIGNAL("clicked()"), self.choose_file)
def choose_file(self):
file_name = QtGui.QFileDialog.getOpenFileName(self, "Open Data File", "", "CSV data files (*.csv)")
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
mainLayout = QtGui.QTabWidget()
ui = Ui_mainLayout()
ui.setupUi(mainLayout)
mainLayout.show()
sys.exit(app.exec_())
This code produces the GUI just fine and everything else works ok including signals. Any idea what I am doing wrong!?
Your class should inherit (directly or indirectly) from QtCore.QObject to be able to handle signals. The first one inherits from QWidget, which does the job.