PyQt4:Can‘t Open My Dialog When I Write My First Code - python

I want to build a dialog with the PyQt4.My compile envirenment is Qt4,Python2 and PyQt4.
I have done something for my job.
1.I complete my UI with Qt Designer and the ui file named dialog.ui.
2.I use the command "pyuic -o ui_dialog.py dialog.ui" to make the python file named ui_dialog.py.
the code of ui_dialog.py is
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dialog.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(516, 378)
self.verticalLayoutWidget = QtGui.QWidget(Dialog)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 13, 501, 361))
self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label_recieve = QtGui.QLabel(self.verticalLayoutWidget)
self.label_recieve.setObjectName(_fromUtf8("label_recieve"))
self.verticalLayout.addWidget(self.label_recieve)
self.textBrowser_recieve = QtGui.QTextBrowser(self.verticalLayoutWidget)
self.textBrowser_recieve.setObjectName(_fromUtf8("textBrowser_recieve"))
self.verticalLayout.addWidget(self.textBrowser_recieve)
self.label_send = QtGui.QLabel(self.verticalLayoutWidget)
self.label_send.setObjectName(_fromUtf8("label_send"))
self.verticalLayout.addWidget(self.label_send)
self.textEdit_send = QtGui.QTextEdit(self.verticalLayoutWidget)
self.textEdit_send.setObjectName(_fromUtf8("textEdit_send"))
self.verticalLayout.addWidget(self.textEdit_send)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.pushButton_send = QtGui.QPushButton(self.verticalLayoutWidget)
self.pushButton_send.setObjectName(_fromUtf8("pushButton_send"))
self.horizontalLayout.addWidget(self.pushButton_send)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "chat", None))
self.label_recieve.setText(_translate("Dialog", "recieve", None))
self.label_send.setText(_translate("Dialog", "send", None))
self.pushButton_send.setText(_translate("Dialog", "SEND", None))
3.I try to write the main.py file and compile it.
My code of main.py is
'''
title:chat dialog
author:CCBANG
virsion:0.1
'''
from PyQt4 import QtCore,QtGui
import sys
from ui_dialog 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 ChatDialog(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self=Ui_Dialog()
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
myqq=ChatDialog()
myqq.show()
sys.exit(app.exec_())
In the main.py ,I don't know how to write "setupUI()" in the "Class ChatDialog"
How can i finish my code ? I would be happy if you can help me. Thanks

With this method of using Qt Designer created python files, generally, your class will inherit the Ui_Dialog class.
class ChatDialog(QtGui.QDialog, Ui_Dialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
Sometimes, people won't inherit, but will assign it to an attribute of the class:
class ChatDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)

Related

Change the text of a label after clicking a button

I do not get why the text of my label is not updating after clicking a button. If I want to show the output on the console, there is no problem.
import sys
from qtpy import QtWidgets
from UI.mainwindow import Ui_MainWindow
app = QtWidgets.QApplication(sys.argv)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.calc_btn.clicked.connect(self.on_calc_btn_click)
def on_calc_btn_click(self):
weight = int(self.ui.weight_textbox.text())
height = int(self.ui.height_textbox.text())
bmi = weight/height**2
print(str(bmi)) # -> works
self.ui.bmi_label.setText(str(bmi)) # -> label does not update
window = MainWindow()
window.show()
sys.exit(app.exec_())
#Try This
from PyQt4 import QtCore, QtGui
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 Ui_CalcBMI(object):
def setupUi(self, CalcBMI):
CalcBMI.setObjectName(_fromUtf8("CalcBMI"))
CalcBMI.resize(400, 300)
self.pushButton = QtGui.QPushButton(CalcBMI)
self.pushButton.setGeometry(QtCore.QRect(140, 220, 111, 28))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(self.On_Update_Clicked)
#add textbox here to get height and weight
self.label = QtGui.QLabel(CalcBMI)
self.label.setGeometry(QtCore.QRect(150, 70, 131, 101))
self.label.setObjectName(_fromUtf8("label"))
self.retranslateUi(CalcBMI)
def On_Update_Clicked(self):
#Get values from textbox and calculate bmi here
bmi="23.5"
self.label.setText(bmi)
def retranslateUi(self, CalcBMI):
CalcBMI.setWindowTitle(_translate("CalcBMI", "CalcBMI", None))
self.pushButton.setText(_translate("CalcBMI", "Calculate now", None))
self.label.setText(_translate("CalcBMI", "inProgess", None))
if __name__ == "__main__":
import sys
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtGui.QApplication(sys.argv)
CalcBMI = QtGui.QWidget()
ui = Ui_CalcBMI()
ui.setupUi(CalcBMI)
CalcBMI.show()
sys.exit(app.exec_())

Automatic update of date and time in python

List item
I am trying to display on my windows current date and time.date and time is not updating automatically.when I am closing and running my python file its fetching the system date and time.please find my code on below
import datetime
import threading
now = datetime.datetime.now()
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.label = QtGui.QLabel(Form)
self.label.setGeometry(QtCore.QRect(100, 110, 241, 17))
self.label.setObjectName(_fromUtf8("label"))
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.timer = QtCore.QTimer()
self.timer.start(10 * 1000) # 10 seconds
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.label.setText(_translate("Form",QtCore.now.strftime("%Y-%m-%d %H:%M"), None))
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 must create a timer that runs from time to time, and call the retranslateUi function.
timer = QtCore.QTimer(Form)
timer.timeout.connect(lambda: ui.retranslateUi(Form))
timer.start(1000)
We must update the time in retranslateUi for it we modify it to:
def retranslateUi(self, Form):
now = datetime.datetime.now()
Form.setWindowTitle(_translate("Form", "Form", None))
self.label.setText(_translate("Form",now.strftime("%Y-%m-%d %H:%M"), None))
complete code:
import datetime
now = datetime.datetime.now()
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.label = QtGui.QLabel(Form)
self.label.setGeometry(QtCore.QRect(100, 110, 241, 17))
self.label.setObjectName(_fromUtf8("label"))
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
now = datetime.datetime.now()
Form.setWindowTitle(_translate("Form", "Form", None))
self.label.setText(_translate("Form",now.strftime("%Y-%m-%d %H:%M"), None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
timer = QtCore.QTimer(Form)
timer.timeout.connect(lambda: ui.retranslateUi(Form))
timer.start(1000)
Form.show()
sys.exit(app.exec_())

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)

Qfiledialog in Pyqt

I'm new to PyQt programming and I've written a code to browse a file. The code is as follows:
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_mainDialog(object):
def setupUi(self, mainDialog):
mainDialog.setObjectName(_fromUtf8("mainDialog"))
mainDialog.resize(648, 48)
self.formLayout = QtGui.QFormLayout(mainDialog)
self.formLayout.setObjectName(_fromUtf8("formLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setContentsMargins(-1, 2, -1, -1)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(mainDialog)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.lineEdit = QtGui.QLineEdit(mainDialog)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.horizontalLayout.addWidget(self.lineEdit)
self.import_2 = QtGui.QPushButton(mainDialog)
self.import_2.setObjectName(_fromUtf8("import_2"))
self.horizontalLayout.addWidget(self.import_2)
self.process = QtGui.QPushButton(mainDialog)
self.process.setObjectName(_fromUtf8("process"))
self.horizontalLayout.addWidget(self.process)
self.formLayout.setLayout(0, QtGui.QFormLayout.FieldRole, self.horizontalLayout)
QtCore.QObject.connect(self.import_2,QtCore.SIGNAL("clicked()"),self.callf)
self.retranslateUi(mainDialog)
QtCore.QMetaObject.connectSlotsByName(mainDialog)
def retranslateUi(self, mainDialog):
mainDialog.setWindowTitle(_translate("mainDialog", "Fatal error check", None))
self.label.setText(_translate("mainDialog", "Import *.f06 file", None))
self.import_2.setText(_translate("mainDialog", "Import", None))
self.process.setText(_translate("mainDialog", "Process", None))
def callf(self):
fileName = QtGui.QFileDialog.getOpenFileName(self, 'import f06 file', '/home/harisyam/Desktop', selectedFilter='*.txt')
if fileName:
print fileName
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
mainDialog = QtGui.QDialog()
ui = Ui_mainDialog()
ui.setupUi(mainDialog)
mainDialog.show()
sys.exit(app.exec_())
When I'm running the code the main dialog comes up but when i press the import button the file chooser was not popping up. Can anyone tell me what is wrong?
The code is big becuase i converted a .ui file into .py. I have desgined the gui in QT designer
Change class Ui_mainDialog(object):
to class Ui_mainDialog(QtGui.QWidget):
Also, there is a spelling mistake.
QtCore.QObject.connect(self.import_2,QtCore.SIGNAL("clciked()"),self.callf)
should be clicked

PyQt4 ---- I want to use closeEvent() in my code

I am python newbie. I am developing pr-room management program.
I think if the user presses the x button , i want to give a warning message .
So, I want to use closeEvent() in first code.
In other words, first code + second code please
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\PJH11\Desktop\dia3.ui'
#
# Created: Sun Aug 17 16:23:08 2014
# by: PyQt4 UI code generator 4.11.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_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(190, 98)
self.pushButton = QtGui.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(0, 0, 191, 101))
font = QtGui.QFont()
font.setPointSize(13)
self.pushButton.setFont(font)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.pushButton.setText(_translate("Dialog", "hi", None))
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_())
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
Your can implement your class to create closeEvent (As your code close event), put them it and create object in main. And your can call to close event by using bool QWidget.close (self).
Full example;
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):
self.Dialog = Dialog
self.Dialog.setObjectName(_fromUtf8("self.Dialog"))
self.Dialog.resize(190, 98)
self.pushButton = QtGui.QPushButton(self.Dialog)
self.pushButton.setGeometry(QtCore.QRect(0, 0, 191, 101))
font = QtGui.QFont()
font.setPointSize(13)
self.pushButton.setFont(font)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi(self.Dialog)
QtCore.QMetaObject.connectSlotsByName(self.Dialog)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL('released()'), self.Dialog.close) # <- put signal to close when clicked.
def retranslateUi(self, Dialog):
self.Dialog.setWindowTitle(_translate("self.Dialog", "self.Dialog", None))
self.pushButton.setText(_translate("self.Dialog", "hi", None))
class QCustomDialog (QtGui.QDialog): # <- Implement your own
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QCustomDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
Regards,

Categories

Resources