Qt QDialog rendering stacked - python

These are my first steps in Qt. I'm trying to build simple text editor like in this tutorial: http://www.rkblog.rk.edu.pl/w/p/simple-text-editor-pyqt4/
So, I've created the design in Qt Designer. Here's the preview:
Perfect :)
Here are Qt Objects and Classes to make it clear how the layout is built:
I've compiled the .py file:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'G:\Google Drive\py_scripts\QTUI\simpleTextEditor_gui.ui'
#
# Created: Fri Jan 24 20:06:32 2014
# by: PyQt4 UI code generator 4.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_simpleTextEditor(object):
def setupUi(self, simpleTextEditor):
simpleTextEditor.setObjectName(_fromUtf8("simpleTextEditor"))
simpleTextEditor.resize(524, 413)
self.gridLayout = QtGui.QGridLayout(simpleTextEditor)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.editorWindow = QtGui.QTextEdit(simpleTextEditor)
self.editorWindow.setObjectName(_fromUtf8("editorWindow"))
self.verticalLayout.addWidget(self.editorWindow)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.buttonOpen = QtGui.QPushButton(simpleTextEditor)
self.buttonOpen.setObjectName(_fromUtf8("buttonOpen"))
self.horizontalLayout.addWidget(self.buttonOpen)
self.buttonClose = QtGui.QPushButton(simpleTextEditor)
self.buttonClose.setObjectName(_fromUtf8("buttonClose"))
self.horizontalLayout.addWidget(self.buttonClose)
self.verticalLayout.addLayout(self.horizontalLayout)
self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
self.retranslateUi(simpleTextEditor)
QtCore.QObject.connect(self.buttonClose, QtCore.SIGNAL(_fromUtf8("clicked()")), simpleTextEditor.close)
QtCore.QMetaObject.connectSlotsByName(simpleTextEditor)
def retranslateUi(self, simpleTextEditor):
simpleTextEditor.setWindowTitle(_translate("simpleTextEditor", "Simple Text Editor", None))
self.buttonOpen.setText(_translate("simpleTextEditor", "Open", None))
self.buttonClose.setText(_translate("simpleTextEditor", "Close", None))
And created my very simple app:
import sys
from PyQt4 import QtCore, QtGui
from simpleTextEditor_gui import Ui_simpleTextEditor
class StartQT4(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_simpleTextEditor()
self.ui.setupUi(self)
# tutaj dajemy wlasne polaczenia slotow
QtCore.QObject.connect(self.ui.buttonOpen,QtCore.SIGNAL("clicked()"), self.file_dialog)
def file_dialog(self):
fd = QtGui.QFileDialog(self)
self.filename = fd.getOpenFileName()
from os.path import isfile
if isfile(self.filename):
text = open(self.filename).read()
self.ui.editorWindow.setText(text)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())
Now when I run the app, all the objects are stacked, which looks like this:
Any help appreciated!

The main problem with your code is that you are using the wrong base-class for your StartQT4 subclass. It should match the top-level class from Qt Designer, which is a QDialog.
You can also simplify your code a little, by adding the ui directly to your sub-class, and by using new-style signal and slot syntax.
With these changes in place, your code would look like this:
import sys
from PyQt4 import QtCore, QtGui
from simpleTextEditor_gui import Ui_simpleTextEditor
class StartQT4(QtGui.QDialog, Ui_simpleTextEditor):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
# tutaj dajemy wlasne polaczenia slotow
self.buttonOpen.clicked.connect(self.file_dialog)
def file_dialog(self):
fd = QtGui.QFileDialog(self)
self.filename = fd.getOpenFileName()
from os.path import isfile
if isfile(self.filename):
text = open(self.filename).read()
self.editorWindow.setText(text)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQT4()
myapp.show()
sys.exit(app.exec_())

Related

PyQt: Can't access inherited verticalLayout - "object has no attribute"

I've created a MainWindow design called Ui_Dashboard within Qt Designer. I've also created a widget called "units_table", which I'd like to import and display within the Ui_Dashboard.
I've created a new class and inherited the Ui_Dashboard class, but for some reason cannot access the verticalLayout object. See code below:
dashboard.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dashboard.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dashboard(object):
def setupUi(self, Dashboard):
Dashboard.setObjectName(_fromUtf8("Dashboard"))
Dashboard.resize(800, 600)
self.centralwidget = QtGui.QWidget(Dashboard)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.widget = QtGui.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(50, 21, 683, 360))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout = QtGui.QVBoxLayout(self.widget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.units_button = QtGui.QPushButton(self.widget)
self.units_button.setCheckable(True)
self.units_button.setChecked(False)
self.units_button.setObjectName(_fromUtf8("units_button"))
self.horizontalLayout.addWidget(self.units_button)
self.calls_button = QtGui.QPushButton(self.widget)
self.calls_button.setCheckable(True)
self.calls_button.setObjectName(_fromUtf8("calls_button"))
self.horizontalLayout.addWidget(self.calls_button)
self.vehicles_button = QtGui.QPushButton(self.widget)
self.vehicles_button.setCheckable(True)
self.vehicles_button.setObjectName(_fromUtf8("vehicles_button"))
self.horizontalLayout.addWidget(self.vehicles_button)
self.persons_button = QtGui.QPushButton(self.widget)
self.persons_button.setCheckable(True)
self.persons_button.setObjectName(_fromUtf8("persons_button"))
self.horizontalLayout.addWidget(self.persons_button)
self.pushButton_6 = QtGui.QPushButton(self.widget)
self.pushButton_6.setCheckable(True)
self.pushButton_6.setObjectName(_fromUtf8("pushButton_6"))
self.horizontalLayout.addWidget(self.pushButton_6)
self.pushButton_4 = QtGui.QPushButton(self.widget)
self.pushButton_4.setCheckable(True)
self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
self.horizontalLayout.addWidget(self.pushButton_4)
self.pushButton_5 = QtGui.QPushButton(self.widget)
self.pushButton_5.setCheckable(True)
self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
self.horizontalLayout.addWidget(self.pushButton_5)
self.verticalLayout.addLayout(self.horizontalLayout)
self.inserted_module = QtGui.QWidget(self.widget)
self.inserted_module.setMinimumSize(QtCore.QSize(481, 321))
self.inserted_module.setObjectName(_fromUtf8("inserted_module"))
self.verticalLayout.addWidget(self.inserted_module)
Dashboard.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(Dashboard)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
self.menubar.setObjectName(_fromUtf8("menubar"))
Dashboard.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(Dashboard)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
Dashboard.setStatusBar(self.statusbar)
self.retranslateUi(Dashboard)
QtCore.QMetaObject.connectSlotsByName(Dashboard)
def retranslateUi(self, Dashboard):
Dashboard.setWindowTitle(_translate("Dashboard", "MainWindow", None))
self.units_button.setText(_translate("Dashboard", "Units", None))
self.calls_button.setText(_translate("Dashboard", "Calls", None))
self.vehicles_button.setText(_translate("Dashboard", "Vehicles", None))
self.persons_button.setText(_translate("Dashboard", "Persons", None))
self.pushButton_6.setText(_translate("Dashboard", "PushButton", None))
self.pushButton_4.setText(_translate("Dashboard", "PushButton", None))
self.pushButton_5.setText(_translate("Dashboard", "PushButton", None))
main.py
import sys
from PyQt4 import QtCore, QtGui, uic
from dashboard import Ui_Dashboard
class MainWindow(QtGui.QMainWindow, Ui_Dashboard):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.units_table = uic.loadUi('units_table.ui', self)
self.inserted_module = self.units_table
self.inserted_module.setMinimumSize(QtCore.QSize(481, 321))
self.verticalLayout.addWidget(self.inserted_module)
self.setupUi(self)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
I'm able to display the imported widget perfectly fine, but I need to add it as a child to the vertical layout, which is where I'm having difficulties. Despite Ui_Dashboard being inherited, I still can't access the verticalLayout.
I keep getting the following error:
AttributeError: 'MainWindow' object has no attribute 'verticalLayout'
verticalLayout does not exist because it is created in the setupUi() method, what you must do is load it before you want to use it. Another mistake is that you should not pass self to loadUi(), since what you will do is reimplement the widget's design:
import sys
from PyQt4 import QtCore, QtGui, uic
from dashboard import Ui_Dashboard
class MainWindow(QtGui.QMainWindow, Ui_Dashboard):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.units_table = uic.loadUi('units_table.ui')
self.verticalLayout.addWidget(self.units_table )
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

pyqt qtabwidget horizontal tab and horizontal text in QtDesigner

i am having problem to change text alignment using pyqt4 desginer i have made tabs horizontal by aligning west but the text in that goes north to south that looks bad i want to change alignment of text as horizontal how can i do that...thanks in advance.
this is my ui.py code
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.tabWidget = QtGui.QTabWidget(self.centralwidget)
self.tabWidget.setTabPosition(QtGui.QTabWidget.West)
self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
self.tab = QtGui.QWidget()
self.tab.setObjectName(_fromUtf8("tab"))
self.tabWidget.addTab(self.tab, _fromUtf8(""))
self.tab_2 = QtGui.QWidget()
self.tab_2.setObjectName(_fromUtf8("tab_2"))
self.tabWidget.addTab(self.tab_2, _fromUtf8(""))
self.tab_3 = QtGui.QWidget()
self.tab_3.setObjectName(_fromUtf8("tab_3"))
self.tabWidget.addTab(self.tab_3, _fromUtf8(""))
self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 31))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Page", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
and this is my main file where i ll add all the functions and from here i generate my window
from untitled import *
from PyQt4 import QtGui # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication
import os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MainWindow(QMainWindow,Ui_MainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The solution that I propose may not be the exact solution but I think it is the one that comes closest. What I propose is to promote the QTabWidget to use a custom QTabWidget.
Before that I have improved the solution proposed in this answer:
tabwidget.py
from PyQt4 import QtGui, QtCore
class HorizontalTabBar(QtGui.QTabBar):
def paintEvent(self, event):
painter = QtGui.QStylePainter(self)
option = QtGui.QStyleOptionTab()
for index in range(self.count()):
self.initStyleOption(option, index)
painter.drawControl(QtGui.QStyle.CE_TabBarTabShape, option)
painter.drawText(self.tabRect(index),
QtCore.Qt.AlignCenter | QtCore.Qt.TextDontClip,
self.tabText(index))
def tabSizeHint(self, index):
size = QtGui.QTabBar.tabSizeHint(self, index)
if size.width() < size.height():
size.transpose()
return size
class TabWidget(QtGui.QTabWidget):
def __init__(self, parent=None):
QtGui.QTabWidget.__init__(self, parent)
self.setTabBar(HorizontalTabBar())
This file will be stored next to the .ui file and the .py files as shown in the following structure:
.
├── main.py # file of class MainWindow(QMainWindow,Ui_MainWindow):
├── tabwidget.py # custom QTabWidget
├── untitled.py
└── untitled.ui # your design
After having the previous structure we open the .ui file with Qt Designer and we right click on the QTabWidget and select promoted to ...:
A dialogue will open and the following should be placed in it:
Then press the add button and then the promote button, and at the end you generate the .py file again with the help of pyuic
At the end you get the following widget:
I know this has been awhile but if anyone needs #Sahil Jain's answer in PyQt5 version, please refer to following for your tabwidget.py
from PyQt5 import QtGui, QtCore, QtWidgets
class HorizontalTabBar(QtWidgets.QTabBar):
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOptionTab()
for index in range(self.count()):
self.initStyleOption(option, index)
painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, option)
painter.drawText(self.tabRect(index),
QtCore.Qt.AlignCenter | QtCore.Qt.TextDontClip,
self.tabText(index))
def tabSizeHint(self, index):
size = QtWidgets.QTabBar.tabSizeHint(self, index)
if size.width() < size.height():
size.transpose()
return size
class TabWidget(QtWidgets.QTabWidget):
def __init__(self, parent=None):
QtWidgets.QTabWidget.__init__(self, parent)
self.setTabBar(HorizontalTabBar())
Using the above method and after that adding a line of code to it and got my icons displayed
from PyQt4 import QtGui, QtCore
class HorizontalTabBar(QtGui.QTabBar):
def paintEvent(self, event):
painter = QtGui.QStylePainter(self)
option = QtGui.QStyleOptionTab()
for index in range(self.count()):
self.initStyleOption(option, index)
painter.drawControl(QtGui.QStyle.CE_TabBarTabShape, option)
painter.drawText(self.tabRect(index),
QtCore.Qt.AlignCenter | QtCore.Qt.TextDontClip,
self.tabText(index))
if index == 0:
painter.drawImage(QtCore.QRectF(10, 10, 66, 67), QtGui.QImage("ico/HOME.png"))
def tabSizeHint(self, index):
size = QtGui.QTabBar.tabSizeHint(self, index)
size.setHeight=50
size.setWidth=200
if size.width() < size.height():
size.transpose()
return size
class TabWidget(QtGui.QTabWidget):
def __init__(self, parent=None):
QtGui.QTabWidget.__init__(self, parent)
self.setTabBar(HorizontalTabBar())
you can add icons as per the indexes of your tabs and set their position accordingly till now this is best solution i can give.cheers
Better way for looks and usability:
At the Qt Designer>
Use QToolBox at left side and QTabWidget at right.
Connect both with signal (currentChanged(int) - setCurrentIndex(int)).
Hide QTabWidget header with following css.
QTabBar::tab {height: 0px;}
Here an Example:

Load QDialog directly from UI-File?

I work with QT Designer and create my GUIs with it. To launch the main program, I use this code:
import sys
from PyQt4 import uic, QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
def main():
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()
app.exec_()
main_dialog = uic.loadUiType("GUI.ui")[0]
class MyWindowClass(QtGui.QMainWindow, main_dialog):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
if __name__ == "__main__":
main()
So with this line main_dialog = uic.loadUiType("GUI.ui")[0] I define my created UI-File.
Now when I work with QDialogs I have only accomplished to run them by first creating them, then converting them to Python code (using PYUIC4), then implementing the code in my main python file and run the QDialog this way:
def NameOfDialog(self):
dialog = Qdialog()
dialog.ui = NameOfDialogClass()
dialog.ui.setupUi(dialog)
dialog.exec_()
The obvious problem is that whenever I make any tiny change to the GUI I have to go through the entire process again (converting and putting the code in the main code and watch out to not delete any other lines that I added and need to maintain).
I am sure there is a solution to also refer to the UI File of the QDialog directly, but how? I tried the same method like I do for the main window but without success :(
Thanks!
EDIT:
Here is what I have tried in a minimal example, but it's not working. What am I missing?
#-*- encoding: UTF-8 -*-
import sys
from PyQt4 import uic, QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
def main():
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()
app.exec_()
main_dialog = uic.loadUiType("GUI.ui")[0]
TestQDialog = uic.loadUiType("Dialog.ui")[0]
class QDialogClass(object, TestQDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
class MyWindowClass(QtGui.QMainWindow, main_dialog):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.btn_close.clicked.connect(self.dialog)
def dialog(self):
dialog = Qdialog()
dialog.ui = QDialogClass()
dialog.ui.setupUi(dialog)
dialog.exec_()
if __name__ == "__main__":
main()
Your dialog class should be defined in exactly the same way as your main-window class. I obviously can't test it myself, but the script should look like this:
import sys
from PyQt4 import uic, QtGui, QtCore
main_dialog = uic.loadUiType("GUI.ui")[0]
TestQDialog = uic.loadUiType("Dialog.ui")[0]
class QDialogClass(QtGui.QDialog, TestQDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
class MyWindowClass(QtGui.QMainWindow, main_dialog):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.btn_close.clicked.connect(self.dialog)
def dialog(self):
dialog = QDialogClass()
dialog.exec_()
def main():
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()
app.exec_()
if __name__ == "__main__":
main()

How do I get variables from my main module in Python?

I am a Structural Engineer by trade and I am trying to automate the creation of 3D models using scripts.
So far I have created three modules; the GUI module using PyQt4, a main module that controls the signals from the GUI, and an export module which "should" pull the variables from main module and generate a script that can be read by my analysis program.
So far the I can't pull the variables from main module when clicking the export menu in the GUI because variable names are not defined.
If I import the main module into the export module to get the variables, I get errors with the Ui_MainWindow.
I have tried to simplify what I am doing below.
main.py module
import sys
from PyQt4 import QtGui, QtCore
from gui import Ui_MainWindow
from export import newFile
class Main(QtGui.QMainWindow):
def __init__(self):
super(Main, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setName()
self.ui.actionExport.triggered.connect(self.exportName)
def exportName(self):
self.exportStaad = newFile().createNewFile()
def setName(self):
self.ui.tbo_Name.textChanged.connect(self.name_Changed)
def name_Changed(self):
someName = self.ui.tbo_Name.text()
print('Name = ' + someName)
app = QtGui.QApplication(sys.argv)
form = Main()
form.show()
app.exec_()
gui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.tbo_Name = QtGui.QLineEdit(self.centralwidget)
self.tbo_Name.setGeometry(QtCore.QRect(80, 60, 150, 20))
self.tbo_Name.setObjectName(_fromUtf8("tbo_Name"))
self.lab_Name = QtGui.QLabel(self.centralwidget)
self.lab_Name.setGeometry(QtCore.QRect(30, 60, 40, 20))
self.lab_Name.setObjectName(_fromUtf8("lab_Name"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuFile = QtGui.QMenu(self.menubar)
self.menuFile.setObjectName(_fromUtf8("menuFile"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.actionExport = QtGui.QAction(MainWindow)
self.actionExport.setObjectName(_fromUtf8("actionExport"))
self.menuFile.addAction(self.actionExport)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.lab_Name.setText(_translate("MainWindow", "Name:", None))
self.menuFile.setTitle(_translate("MainWindow", "File", None))
self.actionExport.setText(_translate("MainWindow", "Export", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
export.py
import sys
from PyQt4 import QtGui, QtCore
from os import path
import math
class newFile():
def createNewFile(dest):
'''
Creates file
'''
name = QtGui.QFileDialog.getSaveFileName ()
f = open(name, 'w')
f.write('Hello' + someName)
f.close
The method called createNewFile(dest) inside the class newFile uses undefined var someName at f.write('Hello' + someName).
This causes the error as it is not defined in the class. Define a variable before you use it.

Pyqt4 QFileDialog Constructor: what to use as parent parameter?

I'm using pyqt4 and python 2.7.11. I have a problem with the file/directory dialogs: I don't know what to use as the parent parameter.
If I use "self" or "None", PyCharm tells me that it's expecting "QFileDialog", and it got "AppTest" and "None" instead, respectively.
If I use "parent=self" or "parent=None", PyCharm tells me that the "self" parameter is unfilled.
Please see the example code below; I'm using Qt Designer to create the ui, let me know if you need that code as well.
import sys
from PyQt4 import QtGui
import ui_test as main_frame
class AppTest(QtGui.QMainWindow, main_frame.Ui_MainAppWindow):
def __init__(self, parent=None):
super(AppTest, self).__init__(parent)
self.setupUi(self)
self.pushButton1.clicked.connect(self.dialog1)
self.show()
def dialog1(self):
file1 = str(QtGui.QFileDialog.getOpenFileName(
parent=self,
caption="Locate file 1",
directory="",
filter="Graphics files (*.jpg *.jpeg)"))
print file1
def main():
app = QtGui.QApplication(sys.argv)
gui = AppTest()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
EDIT: Here's the code for the ui:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test_ui.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainAppWindow(object):
def setupUi(self, MainAppWindow):
MainAppWindow.setObjectName(_fromUtf8("MainAppWindow"))
MainAppWindow.resize(269, 195)
self.centralwidget = QtGui.QWidget(MainAppWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.pushButton1 = QtGui.QPushButton(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton1.sizePolicy().hasHeightForWidth())
self.pushButton1.setSizePolicy(sizePolicy)
self.pushButton1.setObjectName(_fromUtf8("pushButton1"))
self.verticalLayout.addWidget(self.pushButton1)
self.pushButton2 = QtGui.QPushButton(self.centralwidget)
self.pushButton2.setObjectName(_fromUtf8("pushButton2"))
self.verticalLayout.addWidget(self.pushButton2)
MainAppWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainAppWindow)
QtCore.QMetaObject.connectSlotsByName(MainAppWindow)
def retranslateUi(self, MainAppWindow):
MainAppWindow.setWindowTitle(_translate("MainAppWindow", "MainWindow", None))
self.pushButton1.setText(_translate("MainAppWindow", "PushButton1", None))
self.pushButton2.setText(_translate("MainAppWindow", "PushButton2", None))

Categories