Load QDialog directly from UI-File? - python

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

Related

access image from URL in pushbutton in pyqt4 [Python]

I'm trying to add image to pushbutton directly from using the URL in pyqt4. To which i'm unsuccessful.adding the image from the image stored in system is possible.Hence any suggestions or advice would be grateful.
Thank you
`import sys
from PyQt4 import 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)
class Entry_view(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(25, 25, 800, 480)
timer = QTimer()
t1 = QtGui.QPushButton("Tool1",self)
font = QtGui.QFont()
t1.setFont(font)
t1.setObjectName(_fromUtf8("t1"))
icon1 = QtGui.QIcon() # Image has been added to the tool
icon1.addPixmap(QtGui.QPixmap(_fromUtf8('http://www.siliconsemiconductor.net/images/news/195481055397707.jpg')), QtGui.QIcon.Normal, QtGui.QIcon.Off)
t1.setIcon(icon1)
t1.setIconSize(QtCore.QSize(170, 170))
t1.setObjectName(_fromUtf8("t1"))
# t1.clicked.connect(self.Tool_Image_Ext)
t1.resize(400,255)
t1.move(0, 0)
self.Tool_Image_Ext()
self.show()`
The solution is added in following code.The image in url should be downloaded in a separate file name.
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import QPixmap, QIcon
import urllib
import cStringIO
from urllib import urlopen
import requests
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 Entry_view(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(25, 25, 800, 480)
t1 = QtGui.QPushButton("Tool1",self)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Times New Roman"))
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
t1.setFont(font)
t1.setObjectName(_fromUtf8("t1"))
icon1 = QtGui.QIcon() # Image has been added to the tool
data = urllib.urlretrieve("https://upload.wikimedia.org/wikipedia/en/b/be/Google_Chrome_for_Android-_Android_5.0_Logo.png","image1.png")
icon1.addPixmap(QtGui.QPixmap("D:PythonFolder\Codes\image1.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
t1.setIcon(icon1)
t1.setIconSize(QtCore.QSize(170, 170))
t1.setObjectName(_fromUtf8("t1"))
t1.resize(400,255)
t1.move(0, 0)
self.show()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = Entry_view()
sys.exit(app.exec_())

python qt designer mouse tracking cursor position

I am making a GUI for touchscreen
Pushbuttons in this GUI should generate signal when mouse cursor is on the pushbuttons
But qt designer does not have that kind of signal (I already tried released, clicked, pressed)
Therefore, I think constantly tracking cursor position can be a solution
However, I have no idea how to implement mouse tracking (such as mousemoveEvent) in the code generated by qt designer and pyuic
If I use the mouse tracking code from other examples, it does not work...
Please help me
Here is the code what contains essential parts only
from PyQt4 import QtCore, QtGui
import sys
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 mouseMoveEvent(self, event):
current = QtGui.QCursor.pos()
x = current.x()
y = current.y()
print("Mouse %d %d" % (x,y))
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(1920, 720)
import resources_rc
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.setMouseTracking(True)
MainWindow.show()
sys.exit(app.exec_())
I solved this problem
I used a code from https://github.com/bkach/earthquakeviz/blob/master/pyqt.py
Making one more class is working
Complete code
from PyQt4 import QtCore, QtGui
import sys
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(1920, 720)
MainWindow.setMouseTracking(True)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setMouseTracking(True)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
class MainWIndowTest(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.centralwidget.installEventFilter(self)
def eventFilter(self, object, event):
if (event.type() == QtCore.QEvent.MouseMove):
pos = event.pos()
print("%d, %d" % (pos.x(), pos.y()))
return QtGui.QWidget.eventFilter(self, object, event)
def mouseMoveEvent(self, event):
print("Moved")
import resources_rc
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
win = MainWIndowTest()
win.show()
sys.exit(app.exec_())

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

PyQt QTreeWidget not displaying content

I used the Qt designer to design UI (file: tree_view_widget_ui.py) and I have a class (file: tree_view_widget.py) that creates the widget and shows the data, but data is not displayed. Can anyone tell me what am I doing wrong.
tree_view_widget.py
from tree_view_widget_ui import Ui_Form
class TreeViewWidget(QWidget):
def __init__(self, data2show):
QtGui.QWidget.__init__(self,parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.data2show = data2show
self.addItems(self.ui.treeWidget.invisibleRootItem()) #not sure about this line?
def addItems(self, parent):
column = 0
data_group_1 = self.addParent(parent, column, 'Group1', 'data Clients')
for data in self.data2show:
self.addChild(data_item, column, data.prop1, data.prop2)
def addParent(self, parent, column, title, data):
item = QtGui.QTreeWidgetItem(parent, [title])
item.setData(column, QtCore.Qt.UserRole, data)
item.setChildIndicatorPolicy(QtGui.QTreeWidgetItem.ShowIndicator)
item.setExpanded (True)
return item
def addChild(self, parent, column, title, data):
item = QtGui.QTreeWidgetItem(parent, [title])
item.setData(column, QtCore.Qt.UserRole, data)
return item
And the GUI design file (created with Qt Designer):
tree_view_widget_ui.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("TreeView"))
Form.setEnabled(True)
Form.resize(200, 400)
Form.setFixedSize(200, 400)
self.treeWidget = QtGui.QTreeWidget(Form)
self.treeWidget.setEnabled(True)
self.treeWidget.setGeometry(QtCore.QRect(0, 0, 200, 400))
self.treeWidget.setFrameShadow(QtGui.QFrame.Sunken)
self.treeWidget.setLineWidth(1)
self.treeWidget.setMidLineWidth(0)
self.treeWidget.setAutoScrollMargin(16)
self.treeWidget.setIndentation(1)
self.treeWidget.setRootIsDecorated(True)
self.treeWidget.setUniformRowHeights(True)
self.treeWidget.setAnimated(False)
self.treeWidget.setColumnCount(0)
self.treeWidget.setObjectName(_fromUtf8("treeWidget"))
self.treeWidget.header().setVisible(False)
self.treeWidget.setHeaderHidden(True)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Tree View", "Tree View", None))
self.treeWidget.setSortingEnabled(False)
Any suggestions how to change the code that the data will be displayed in the tree shape?
The reason why you are not seeing any of your added items, is because you have set the column count of the tree-widget to zero (in the GUI module).
To fix this, go back to Qt Designer, select your tree-widget and scroll down to the bottom of the Property Editor. Then select the value for columnCount and click the little red arrow on the right to reset it back to the default.
And don't forget to re-generate your GUI module!

Qt QDialog rendering stacked

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

Categories