PyQt with custom slots works, Qt designer does not - python

I am trying to build a GUI around some code that I already have. I understand how to do this when building the GUI manually, but am stuck when adding this to the python code generated by Qt Designer and pyuic. As an example, I might need a button which will allow the user to point to a file, which manually I do as such, and this works:
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
btn = QtGui.QPushButton('Open File', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.resize(btn.sizeHint())
btn.move(50, 50)
btn.clicked.connect(self.loadFile)
self.setGeometry(300, 300, 250, 150)
self.show()
def loadFile(self):
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
# some custom code for reading file and storing it
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
However, when I try to do the same in Qt Designer code the program stops before reaching the file dialog.
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_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(400, 300)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(130, 100, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi(Form)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.loadFile)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.pushButton.setText(_translate("Form", "Open File", None))
def loadFile(self):
print('loadFile1')
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
print('loadFile2')
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
This only prints the first statement in loadFile(), but does not open up the file dialog window. What am I doing wrong?

According to the documentation:
QString getOpenFileName (QWidget parent = None, QString caption = '',
QString directory = '', QString filter = '', Options options = 0)
QString getOpenFileName (QWidget parent = None, QString caption = '',
QString directory = '', QString filter = '', QString selectedFilter =
'', Options options = 0)
You need to pass as a parent a widget or None, in your case self is not of type object.
You must change
QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
to
QtGui.QFileDialog.getOpenFileName(None, 'Open file', '/home')

I really don't like using pyuic as long as I can avoid. There's an easier way you may try, it reduces your code. Say your UI file is called something.ui, and you have named your button in QT Designer somebutton, then the code will be:
from PyQt4 import QtCore, QtGui, uic
Ui_somewindow, _ = uic.loadUiType("something.ui") #the path to your UI
class SomeWindow(QtGui.QMainWindow, Ui_somewindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_somewindow.__init__(self)
self.setupUi(self)
self.somebutton.clicked.connect(self.loadFile)
def loadFile(self):
print('loadFile1')
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
print('loadFile2')
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = SomeWindow()
window.show()
sys.exit(app.exec_())
Note that if you have QDialog replace QMainWindow with QDialog.
Hope this helps.

Related

Event fired twice using button box in Pyqt

This app is a basic Drag'n'Drop program and should handle dropped .html files.
So far I have written this code:
main.py
from PyQt4 import QtGui
import sys
import design, os
class MyTextEdit(QtGui.QTextEdit):
def __init__(self, parent):
super(MyTextEdit, self).__init__(parent)
self.setAcceptDrops(True)
self.list_of_dropped_files = []
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
event.accept()
def dropEvent(self, event):
self.clear()
self.list_of_dropped_files = event.mimeData().urls()
for single_file in self.list_of_dropped_files:
self.append(single_file.toLocalFile())
class DialogInit(QtGui.QDialog, design.Ui_Dialog):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.buttonBox.accepted.connect(self.accept) # handle the ok button click
self.textEditHandler = MyTextEdit(self.textEdit)
def accept(self):
print self.textEditHandler.list_of_dropped_files
def main():
app = QtGui.QApplication(sys.argv)
form = DialogInit()
form.show()
app.exec_()
if __name__ == '__main__':
main()
and I created also a design.py code using the QtDesigner that looks like as follows:
# -*- coding: utf-8 -*-
# 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_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(409, 80)
self.verticalLayoutWidget = QtGui.QWidget(Dialog)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 401, 71))
self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.textEdit = QtGui.QTextEdit(self.verticalLayoutWidget)
self.textEdit.setAcceptDrops(True)
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.horizontalLayout.addWidget(self.textEdit)
self.verticalLayout.addLayout(self.horizontalLayout)
self.buttonBox = QtGui.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.verticalLayout.addWidget(self.buttonBox)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label.setText(_translate("Dialog", "Drop .html file(s):", None))
However, after the Ok button from the button box has been pressed, the event and therefore the function accept(), is fired twice.
Furthermore I found that after dropping several files into the QTextEdit, the widget doesn't change its height or at least a scroll pane is added automatically.
Any ideas how to fix the both issues?
I think also that my code is pretty messed up, it works, but it is not really well programmed.
Can someone please give an advice how to refactor the code? What could I have been better?
Thanks!
I've found myself a solution for closing the QDialog issue after the ok button has been clicked. I had to remove the accept() slot in the design.py.
However, I still can't see a scrollbar added when several files have been droppped.

Why does widget close instantly?

I'm trying to get a widget created in Qt designer to be called from a menu option from my QMainWindow class in a different script. So far it just exits instantly. I was wondering if anybody could tell me what I'm doing wrong? Do I need to call a subprocess?
Here is the relevant parts of the scripts:
Main Script:
import sys
from PyQt4 import QtGui
from lib import Step1_Import_data
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
openEditor = QtGui.QAction("&Editor",self)
openEditor.setShortcut("Ctrl+E")
openEditor.triggered.connect(self.editor)
self.statusBar()
mainMenu = self.menuBar()
editorMenu = mainMenu.addMenu('&Editor')
editorMenu.addAction(openEditor)
self.showMaximized()
def editor(self):
Form = QtGui.QWidget()
ui = Step1_Import_Data.Ui_Form()
widget = ui.setupUi(Form)
Form.show()
self.setCentralWidget(widget)
def main():
app = QtGui.QApplication(sys.argv)
GUI = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
And then this is my script Step1_Import_Data.py
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_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(826, 536)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(680, 10, 131, 41))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
"""
Loads more stuff...
"""
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.pushButton.setText(_translate("Form", "Step 2: Data Checking", None))
"""
More stuff redacted to be concise
"""
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
You need to keep a reference to the child window, otherwise it will be immediately garbage-collected when the function returns:
class MainWindow(QtGui.QMainWindow):
def __init__(self):
...
self.editorWindow = None
def editor(self):
if self.editorWindow is None:
self.editorWindow = EditorWindow()
self.editorWindow.show()
class EditorWindow(QtGui.QWidget):
def __init__(self):
super(EditorWindow, self).__init__()
self.ui = Step1_Import_data.Ui_Form()
self.ui.setupUi(self)

PyQt4 file copy progress bar with QThread

I am creating an application which require multiple file copy and large file copy operation. Earlier I used python threading along with QtGui.qApp.processEvents() to make GUI responsive. Now I want to shift to QThread for better thread handling. Here is the mock code I am planning to implement. Some functions are not complete but the concept is here. Basically I would like to copy large file to external drives and calculate/monitor the free size of external drive to update progressbar. Here is the code generated with Qt Designer ui_progress.py:-
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'progress.ui'
#
# Created: Tue Jan 20 21:19:13 2015
# by: PyQt4 UI code generator 4.10.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_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(400, 100)
self.gridLayout_2 = QtGui.QGridLayout(Dialog)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label = QtGui.QLabel(Dialog)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.progressBar = QtGui.QProgressBar(Dialog)
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.gridLayout_2.addWidget(self.progressBar, 1, 0, 1, 1)
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.gridLayout_2.addWidget(self.pushButton, 2, 0, 1, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label.setText(_translate("Dialog", "File copy info here.", None))
self.pushButton.setText(_translate("Dialog", "Start", None))
Here is my test.py to mock the file copy operation. Here I have not used size of external disk but gone for range of numbers to check the logic:-
from PyQt4 import QtCore
from PyQt4 import QtGui
from gui.ui_progress import Ui_Dialog
import sys
import time, os
import shutil
source = "path/to/my/large/file"
dest = "path/to/destination/directory"
class ProgessGui(QtGui.QDialog, Ui_Dialog):
global source
global dest
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.test)
def get_zize(self, path):
return os.path.getsize(path)
def copy_file(self, source, dest):
# I keep all my multiple copy operation in this function.
try:
shutil.copy(source, dest)
if some_condition:
#copy other file
except:
print "File copy failed..."
def test(self):
self.ui.progressBar.setValue(0)
self.copy_file(source, dest)
self.workThread = WorkThread()
self.workThread.start()
class WorkThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
while self.alive:
for i in range(20):
time.sleep(0.13)
self.emit(QtCore.SIGNAL("progress(int)"), i)
return
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = ProgessGui()
myapp.show()
sys.exit(app.exec_())
When I run the above code, progressbar is set to 0 but I get the following error:-
self.workThread = WorkThread()
NameError: global name 'WorkThread' is not defined
I think I have got two problem here. Any help is appreciated.
Edit 1
Corrected the code above. Now the error message has gone. But the progress bar is set to 0 percent and not moving ahead.

Save the selections made in the qcombobox in pyqt

I'm new to Pyqt programming. i tried to build a simple GUI which looks like the one in the picture:
This is the code which i wrote:
from PyQt4 import QtCore, QtGui
import subprocess
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_Dialog(object):
Ui_Dialog.hypermesh =0
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(435, 181)
self.gridLayout_2 = QtGui.QGridLayout(Dialog)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.groupBox = QtGui.QGroupBox(Dialog)
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.gridLayout = QtGui.QGridLayout(self.groupBox)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.pushButton = QtGui.QPushButton(self.groupBox)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
self.comboBox = QtGui.QComboBox(self.groupBox)
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.gridLayout.addWidget(self.comboBox, 0, 1, 1, 1)
self.pushButton_3 = QtGui.QPushButton(self.groupBox)
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.gridLayout.addWidget(self.pushButton_3, 1, 0, 1, 1)
self.pushButton_2 = QtGui.QPushButton(self.groupBox)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.gridLayout.addWidget(self.pushButton_2, 1, 1, 1, 1)
self.gridLayout_2.addWidget(self.groupBox, 0, 0, 1, 1)
hypmv=[]
cont=subprocess.Popen('ls /usr/local/bin/hm*',stdout=subprocess.PIPE,stdin=subprocess.PIPE,shell=True)
contents = cont.stdout.readlines()
for i in range(len(contents)):
temp=contents[i].strip()
temp=temp.split('/')
size=len(temp)
hypmv.append(temp[size-1])
self.comboBox.addItem(_fromUtf8(""))
self.comboBox.setItemText(i, _translate("Dialog", hypmv[i], None))
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8("clicked()")), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
QtCore.QObject.connect(self.pushButton,QtCore.SIGNAL(_fromUtf8("clicked()")),self.hypm)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.groupBox.setTitle(_translate("Dialog", "Software Selector", None))
self.pushButton.setText(_translate("Dialog", "Hypermesh(Pre processor)", None))
self.pushButton_3.setText(_translate("Dialog", "Quit", None))
self.pushButton_2.setText(_translate("Dialog", "Save", None))
def hypm(self):
Ui_Dialog.hypermesh = unicode(self.comboBox.currentText())
subprocess.Popen(Ui_Dialog.hypermesh,shell=True)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
In the code the combobox items are intialized when the gui intializes and when i hit the button should open the software version which was selected in the combobox currently. this function it's doing pretty good.
But now i want to save the selection made by the user so that every time he invokes the gui he shouldn't select again the version previously he used in the combobox.
so if he selects hm_11.0 for the first time it should be everytime "hm_11.0" until he changes it. How can i do this??
This is the class you want to be reading: http://pyqt.sourceforge.net/Docs/PyQt4/qsettings.html
There is like a small tutorial inside (ctrl+f Restoring the State of a GUI Application).
You will use setValue to store information with par keyToSetting/valueOfSetting and reading with value keyToSetting.
Example:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.readSettings()
self.setWindowTitle('Simple')
self.show()
def readSettings(self):
settings = QtCore.QSettings("AyaanTech", "SoftwareTest")
self.setGeometry(settings.value("geometry", QtCore.QRect(300, 300, 250, 150)).toRect());
def writeSettings(self):
settings = QtCore.QSettings("AyaanTech", "SoftwareTest")
settings.setValue("geometry", self.geometry());
def closeEvent(self, event):
quit_msg = "Do you want to save position and size?"
reply = QtGui.QMessageBox.question(self, 'Message',
quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel)
if reply == QtGui.QMessageBox.Yes:
self.writeSettings()
event.accept()
elif reply == QtGui.QMessageBox.No:
event.accept()
else:
event.ignore()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

PyQT: LineEdit over QTextEdit

Okay, I really need help with this... I have a dockwidget, and in that dockwidget I have a textedit. Ok, all is fine so far, and here is the code for that:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'out/untitled.ui'
#
# Created: Mon Sep 16 19:33:15 2013
# by: PyQt4 UI code generator 4.10.2
#
# 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(320, 240)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
MainWindow.setCentralWidget(self.centralwidget)
self.dockWidget = QtGui.QDockWidget(MainWindow)
self.dockWidget.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures)
self.dockWidget.setObjectName(_fromUtf8("dockWidget"))
self.textEdit = QtGui.QTextEdit()
self.textEdit.setGeometry(QtCore.QRect(40, 10, 104, 71))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.dockWidget.setWidget(self.textEdit)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QMainWindow()
f = Ui_MainWindow()
f.setupUi(Form)
Form.show()
sys.exit(app.exec_())
Now, what I want to do is place a line edit at the bottom of the window (or dockwidget) that, overlaps the text area, doesn't move when the dockwidget is resized, and fills the whole dockwidget. I have tried this:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'out/untitled.ui'
#
# Created: Mon Sep 16 19:33:15 2013
# by: PyQt4 UI code generator 4.10.2
#
# 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(320, 240)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
MainWindow.setCentralWidget(self.centralwidget)
self.dockWidget = QtGui.QDockWidget(MainWindow)
self.dockWidget.setFeatures(QtGui.QDockWidget.NoDockWidgetFeatures)
self.dockWidget.setObjectName(_fromUtf8("dockWidget"))
self.textEdit = QtGui.QTextEdit()
self.textEdit.setGeometry(QtCore.QRect(40, 10, 104, 71))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.dockWidget.setWidget(self.textEdit)
QtGui.QLineEdit(self.dockWidget) # Line edit
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(8), self.dockWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QMainWindow()
f = Ui_MainWindow()
f.setupUi(Form)
Form.show()
sys.exit(app.exec_())
but it is not what I want. I REALLY need to get this working, so any help would be great. Thank you.
Here is an example of how to display a widget on top of another:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#---------
# IMPORT
#---------
import sys
from PyQt4 import QtGui, QtCore
#---------
# DEFINE
#---------
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.pushButtonInput = QtGui.QPushButton(self)
self.pushButtonInput.setText("Toggle the QLineEdit widget!")
self.pushButtonInput.clicked.connect(self.on_pushButtonInput_clicked)
self.textEditInput = QtGui.QTextEdit(self)
self.textEditInput.setText("This is a QTextEdit widget.")
self.textEditInput.installEventFilter(self)
self.lineEditInput = QtGui.QLineEdit(self)
self.lineEditInput.setText("This is a QLineEdit widget.")
self.lineEditInput.hide()
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.pushButtonInput)
self.layoutVertical.addWidget(self.textEditInput)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.Resize:
geometry = self.textEditInput.geometry()
self.lineEditInput.setGeometry(geometry)
return super(MyWindow, self).eventFilter(obj, event)
#QtCore.pyqtSlot()
def on_pushButtonInput_clicked(self):
if self.lineEditInput.isVisible():
self.lineEditInput.hide()
else:
self.lineEditInput.show()
#---------
# MAIN
#---------
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())

Categories

Resources