python qt4 isn't working - python

I have watched this video and then i created succesfully hello.py. But i run hello.py , doesn't show a form. I need to help. I haven't taken any error ever.
After I have created interface in qt designer,i created hello.py script. "C:\Python27\Lib\site-packages\PyQt4\pyuic4.bat" hello.ui -o hello.py
The codes is below :
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(509, 312)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayout.addWidget(self.label)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.lineEdit = QtGui.QLineEdit(Form)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.horizontalLayout.addWidget(self.lineEdit)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.verticalLayout.addLayout(self.horizontalLayout)
self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.label.clear)
QtCore.QObject.connect(self.lineEdit, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.label.setText)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.lineEdit.clear)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.label.setText(_translate("Form", "Hello World", None))
self.pushButton.setText(_translate("Form", "PushButton", None))

You need to instantiate your object and set it up. Adding this at the bottom of your current code will show the form.
import sys
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
def execute_event(self):
pass
def execute_all_event(self):
pass
def reload_event(self):
pass
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
This answer was from a similar question.

Related

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

PyQt4 AttributeError: 'function' object has no attribute 'self'

I can't change the values in the GUI table from the main program. I get an error
AttributeError: 'function' object has no attribute 'commandTable'
I have read and tried the solution shown in this question and it did not work.
AttributeError: 'function' object has no attribute 'self'
What should I change in my code to get the code to work?
Main code:
import sys
from PyQt4 import QtCore, QtGui
from GUI_Window import *
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.setupUi.commandTable.setItem(0,0, QtGui.QTableWidgetItem('1'))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
gui 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(821, 544)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.table = QtGui.QTableWidget(self.centralwidget)
self.table.setRowCount(0)
self.table.setObjectName(_fromUtf8("table"))
self.table.setColumnCount(0)
self.gridLayout.addWidget(self.table, 0, 0, 1, 1)
self.label = QtGui.QLabel(self.centralwidget)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 2, 0, 1, 1)
self.progressBar = QtGui.QProgressBar(self.centralwidget)
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.gridLayout.addWidget(self.progressBar, 2, 1, 1, 1)
self.commandTable = QtGui.QTableWidget(self.centralwidget)
self.commandTable.setEnabled(True)
self.commandTable.setAlternatingRowColors(False)
self.commandTable.setRowCount(2)
self.commandTable.setColumnCount(10)
self.commandTable.setObjectName(_fromUtf8("commandTable"))
self.commandTable.setItem(0,0, QtGui.QTableWidgetItem('hi'))
self.commandTable.horizontalHeader().setCascadingSectionResizes(False)
self.commandTable.horizontalHeader().setSortIndicatorShown(False)
self.commandTable.horizontalHeader().setStretchLastSection(False)
self.commandTable.verticalHeader().setCascadingSectionResizes(False)
self.gridLayout.addWidget(self.commandTable, 1, 0, 1, 2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 821, 18))
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)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.label.setText(_translate("MainWindow", "TextLabel", None))
Sorry that the last part isnt well formatted
You're trying to call your commandTable on the setupUi() method. It's a method so it doesn't have any such property. Instead try:
self.ui.commandTable.setItem(0,0, QtGui.QTableWidgetItem('1'))
in your MyForm.__init__() method. The object containing references to your elements is self.ui, not its methods.

QLineEdit doesn't show up

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(456, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.Applicant_Name = QtGui.QLineEdit(self.centralwidget)
self.Applicant_Name.setGeometry(QtCore.QRect(40, 30, 161, 21))
self.Applicant_Name.setObjectName(_fromUtf8("Applicant_Name"))
self.textEdit = TextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(10, 70, 401, 521))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(240, 30, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "file", None))
class TextEdit(QtGui.QTextEdit):
def __init__(self, type, parent=None):
super(TextEdit, self).__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.ignore()
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_())
Hi, I'm new to python. When i run my code, the QTextEdit widget doesn't show up, why does it happen? I want to add drag and drop function in the QTextEdit which can show the text content in a file, Thank you.
def __init__(self, parent):
super(TextEdit, self).__init__(parent)
self.setAcceptDrops(True)

Qt/PyQt GraphicView

I am trying to recreate some pyqt codes using qt designer.I generated a simple python code using pyuic4.The image should load only in the QgraphicView area but it covers the entire window and I could not see the push buttons.
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(608, 526)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.widget = QtGui.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(300, 20, 258, 244))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout = QtGui.QVBoxLayout(self.widget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.graphicsView = QtGui.QGraphicsView(self.widget)
self.graphicsView.setEnabled(True)
self.graphicsView.setMinimumSize(QtCore.QSize(200, 200))
self.graphicsView.setMaximumSize(QtCore.QSize(400, 400))
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.verticalLayout.addWidget(self.graphicsView)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.pushButton_2 = QtGui.QPushButton(self.widget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.horizontalLayout.addWidget(self.pushButton_2)
self.verticalLayout.addLayout(self.horizontalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 608, 22))
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)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "PushButton", None))
self.pushButton_2.setText(_translate("MainWindow", "PushButton", None))
and the main file is :
import sys
from PyQt4 import QtCore, QtGui
from graphics_test_output import Ui_MainWindow
class Main(QtGui.QMainWindow,Ui_MainWindow):
def __init__(self):
super(Main,self).__init__()
self.setupUi(self)
self.mw = MainWidget()
self.setCentralWidget(self.mw)
class MainWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWidget,self).__init__(parent)
self.scene = QtGui.QGraphicsScene()
self.view = QtGui.QGraphicsView(self.scene)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.view)
self.setLayout(layout)
self.pixmap_item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap('Image.png'), None, self.scene)
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
I have added screenshots of ui design and the current output and they would appear.
ui_design:
current_output:

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

Categories

Resources