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()
Related
This question already has answers here:
Creating simple form with qt-designer and pyqt
(1 answer)
QtDesigner changes will be lost after redesign User Interface
(2 answers)
Closed 3 years ago.
I have an issue with my PyQt setup. Whenever I load my script, I got this message popping.
QLayout: Attempting to add QLayout "" to Ingest "Ingest", which already has a layout
That's my first time trying to implement a Promoted Widget and I'm not very experimented yet with PyQt. Essentially, I'm loading my 'MainWindow', which gets its promoted widget 'Ingest'.
I've done my interfaces using QtDesigner and I convert my .ui using pyuic4 into .py.
The main problem looks to be somewhere between my promoted tab "Ingest" and the "Ingest" widget itself.
Your help will be very appreciated!
Here's my whole thing (stripped of all the unrelated commands). Please don't mind if it's a little bit messy.
First, my opening script:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from python.mainwindow import MainWindow
def main():
app = QApplication(sys.argv)
app.processEvents()
mw = MainWindow()
mw.show()
app.exec_()
if __name__ == '__main__':
main()
This calls my MainWindow script.
MainWindow class:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from .ui.mainwindow import Ui_MainWindow
from styleSheets import styleSheets
import some_other_imports
class MainWindow(QMainWindow,Ui_MainWindow):
def __init__(self,parent = None):
super(MainWindow,self).__init__(parent)
self.setupUi(self)
self.setWindowTitle("Project Manager")
#self.setWindowIcon(QIcon("some/path/icon.png"))
#self.some_other_commands('foo')
#self.this_dir = os.path.dirname(__file__)
def some_other_commands(self,some_arg):
return some_arg
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.setEnabled(True)
MainWindow.resize(948, 540)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(948, 540))
MainWindow.setMaximumSize(QtCore.QSize(948, 16777215))
MainWindow.setDockOptions(QtGui.QMainWindow.AllowTabbedDocks|QtGui.QMainWindow.AnimatedDocks)
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.setObjectName(_fromUtf8("tabWidget"))
# PROJECT TAB
self.project_tab = QtGui.QWidget()
self.project_tab.setObjectName(_fromUtf8("project_tab"))
self.gridLayout_5 = QtGui.QGridLayout(self.project_tab)
self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout_5.addItem(spacerItem, 2, 3, 1, 1)
self.projects_listWidget = QtGui.QListWidget(self.project_tab)
self.gridLayout_5.addWidget(self.projects_listWidget, 0, 0, 1, 2)
self.tabWidget.addTab(self.project_tab, _fromUtf8(""))
# SEQ/SHOT TAB
self.seqshots_tab = QtGui.QWidget()
self.seqshots_tab.setObjectName(_fromUtf8("seqshots_tab"))
self.horizontalLayout = QtGui.QHBoxLayout(self.seqshots_tab)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.gridLayout_2 = QtGui.QGridLayout()
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.treeWidget = QtGui.QTreeWidget(self.seqshots_tab)
self.treeWidget.setAnimated(True)
self.treeWidget.setObjectName(_fromUtf8("treeWidget"))
self.gridLayout_2.addWidget(self.treeWidget, 1, 0, 1, 4)
self.tabWidget.addTab(self.seqshots_tab, _fromUtf8(""))
# INGEST TAB
# *** PROBLEMATIC TAB ***
self.ingest_tab = Ingest(self.tabWidget)
self.ingest_tab.setObjectName(_fromUtf8("ingest_tab"))
self.tabWidget.addTab(self.ingest_tab, _fromUtf8(""))
# SETTINGS TAB
self.settings_tab = QtGui.QWidget()
self.settings_tab.setObjectName(_fromUtf8("settings_tab"))
self.tabWidget.addTab(self.settings_tab, _fromUtf8(""))
self.gridLayout.addWidget(self.tabWidget, 0, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(2)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "Project Manager", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.project_tab), _translate("MainWindow", "Project", None))
self.treeWidget.headerItem().setText(0, _translate("MainWindow", "Items", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.seqshots_tab), _translate("MainWindow", "Seq / Shots", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.ingest_tab), _translate("MainWindow", "Ingest", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.settings_tab), _translate("MainWindow", "Settings", None))
from ..ingest import Ingest
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_())
This Ui_MainWindow interface calls the promoted tab 'Ingest'.
And now for the main course, my 'Ingest' widget:
import os,sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from .ui.ingest import Ui_Ingest
class Ingest(QMainWindow,Ui_Ingest):
def __init__(self,parent=None):
super(Ingest,self).__init__(parent)
self.setupUi(self)
self.setWindowTitle("Ingest Tools")
#self.button.currentIndexChanged.connect(self.some_command)
def some_command(self):
return "foo"
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_Ingest(object):
def setupUi(self, Ingest):
Ingest.setObjectName(_fromUtf8("Ingest"))
Ingest.resize(686, 374)
self.horizontalLayout = QtGui.QHBoxLayout(Ingest)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.splitter = QtGui.QSplitter(Ingest)
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName(_fromUtf8("splitter"))
self.widget = QtGui.QWidget(self.splitter)
self.widget.setObjectName(_fromUtf8("widget"))
self.gridLayout_2 = QtGui.QGridLayout(self.widget)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.ingest_project_group = QtGui.QGroupBox(self.widget)
self.ingest_project_group.setTitle(_fromUtf8("Projects"))
self.ingest_project_group.setObjectName(_fromUtf8("ingest_project_group"))
self.gridLayout_7 = QtGui.QGridLayout(self.ingest_project_group)
self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))
self.ingest_project_comboBox = QtGui.QComboBox(self.ingest_project_group)
self.ingest_project_comboBox.setObjectName(_fromUtf8("ingest_project_comboBox"))
self.gridLayout_7.addWidget(self.ingest_project_comboBox, 0, 0, 1, 1)
self.gridLayout_2.addWidget(self.ingest_project_group, 0, 0, 1, 1)
self.ingest_data_group = QtGui.QGroupBox(self.widget)
self.ingest_data_group.setMinimumSize(QtCore.QSize(209, 0))
self.ingest_data_group.setMaximumSize(QtCore.QSize(209, 16777215))
self.ingest_data_group.setTitle(_fromUtf8("Data"))
self.ingest_data_group.setObjectName(_fromUtf8("ingest_data_group"))
self.gridLayout_4 = QtGui.QGridLayout(self.ingest_data_group)
self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))
self.ingest_path = QtGui.QLineEdit(self.ingest_data_group)
self.ingest_path.setMaximumSize(QtCore.QSize(16777215, 25))
self.ingest_path.setText(_fromUtf8(""))
self.ingest_path.setObjectName(_fromUtf8("ingest_path"))
self.gridLayout_4.addWidget(self.ingest_path, 0, 0, 1, 1)
self.ingest_path_button = QtGui.QPushButton(self.ingest_data_group)
self.ingest_path_button.setMinimumSize(QtCore.QSize(25, 0))
self.ingest_path_button.setMaximumSize(QtCore.QSize(25, 16777215))
self.ingest_path_button.setText(_fromUtf8("..."))
self.ingest_path_button.setObjectName(_fromUtf8("ingest_path_button"))
self.gridLayout_4.addWidget(self.ingest_path_button, 0, 1, 1, 1)
self.ingest_resolutionFolder_checkBox = QtGui.QCheckBox(self.ingest_data_group)
self.ingest_resolutionFolder_checkBox.setToolTip(_fromUtf8("<html><head/><body><p>Check it if there is a resolution folder in each shots.</p><p>Example: [...]/19TWO_VFX_2001-01-01/19TWO_042_010/<span style=\" font-weight:600; text-decoration: underline;\">2048x1152</span>/frame.1001.dpx<br/></p></body></html>"))
self.ingest_resolutionFolder_checkBox.setText(_fromUtf8("Resolution Folder"))
self.ingest_resolutionFolder_checkBox.setObjectName(_fromUtf8("ingest_resolutionFolder_checkBox"))
self.gridLayout_4.addWidget(self.ingest_resolutionFolder_checkBox, 1, 0, 1, 1)
self.ingest_getData_button = QtGui.QCommandLinkButton(self.ingest_data_group)
self.ingest_getData_button.setMaximumSize(QtCore.QSize(150, 16777215))
self.ingest_getData_button.setText(_fromUtf8("Refresh Datas"))
self.ingest_getData_button.setObjectName(_fromUtf8("ingest_getData_button"))
self.gridLayout_4.addWidget(self.ingest_getData_button, 2, 0, 1, 1)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.gridLayout_4.addItem(spacerItem, 7, 0, 1, 1)
self.ingest_update_in_FS_button = QtGui.QCommandLinkButton(self.ingest_data_group)
self.ingest_update_in_FS_button.setMaximumSize(QtCore.QSize(150, 16777215))
self.ingest_update_in_FS_button.setText(_fromUtf8("Update \'in FS\'"))
self.ingest_update_in_FS_button.setObjectName(_fromUtf8("ingest_update_in_FS_button"))
self.gridLayout_4.addWidget(self.ingest_update_in_FS_button, 8, 0, 1, 1)
self.ingest_nameMatchCode = QtGui.QLineEdit(self.ingest_data_group)
self.ingest_nameMatchCode.setToolTip(_fromUtf8("<html><head/><body><p>"</p><p>Use flags to return a naming convention when naming the files or folders in a project. Always separate the flags with underscors ( _ ).<br/>example: <proj>_<0>_<seq>_<shot></p><p>FLAGS<br/><0> : Null info. Put this if there\'s a place with nothing to get.<br/><proj> : Indicates the abreviation or name of the project. <br/><seq> : Gets the name of the sequence. Insert this multiple times if the sequence has multiple sections.<br/><shot> : Gets the name of the shot. Insert this multiple times if the shot has multiple sections.</p><p>"</p></body></html>"))
self.ingest_nameMatchCode.setText(_fromUtf8(""))
self.ingest_nameMatchCode.setObjectName(_fromUtf8("ingest_nameMatchCode"))
self.gridLayout_4.addWidget(self.ingest_nameMatchCode, 4, 0, 1, 2)
self.ingest_nameMatchCode_label = QtGui.QLabel(self.ingest_data_group)
self.ingest_nameMatchCode_label.setText(_fromUtf8("Name Match Code:"))
self.ingest_nameMatchCode_label.setObjectName(_fromUtf8("ingest_nameMatchCode_label"))
self.gridLayout_4.addWidget(self.ingest_nameMatchCode_label, 3, 0, 1, 2)
self.gridLayout_2.addWidget(self.ingest_data_group, 1, 0, 1, 1)
self.ingest_shot_table = QtGui.QTableWidget(self.splitter)
self.ingest_shot_table.setMinimumSize(QtCore.QSize(250, 0))
self.ingest_shot_table.setObjectName(_fromUtf8("ingest_shot_table"))
self.ingest_shot_table.setColumnCount(0)
self.ingest_shot_table.setRowCount(0)
self.widget1 = QtGui.QWidget(self.splitter)
self.widget1.setObjectName(_fromUtf8("widget1"))
self.verticalLayout = QtGui.QVBoxLayout(self.widget1)
self.verticalLayout.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.pushButton = QtGui.QPushButton(self.widget1)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout.addWidget(self.pushButton)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.verticalLayout.addItem(spacerItem1)
self.horizontalLayout.addWidget(self.splitter)
self.retranslateUi(Ingest)
QtCore.QMetaObject.connectSlotsByName(Ingest)
def retranslateUi(self, Ingest):
Ingest.setWindowTitle(_translate("Ingest", "Form", None))
self.pushButton.setText(_translate("Ingest", "PushButton", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Ingest = QtGui.QWidget()
ui = Ui_Ingest()
ui.setupUi(Ingest)
Ingest.show()
sys.exit(app.exec_())
Uhhh... Can somebody please help me with this? I can't seem to catch the minimize event of a widget I created. I tried solutions from every post I could find but it just doesn't seem to work with my code. In one of the solutions I tried, the window minimized and the system tray icon shows up but the app icon is still visible on the taskbar. I can't seem to figure out what I should be doing or what I'm missing here. I'm using Python 2.7 and PyQt 4.11. My OS is Windows 7 so I'm pretty sure its not an os issue. I'd really appreciate it if someone could help me here.
Here is the code.
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_Form(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi(self)
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(385, 277)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.radioButton = QtGui.QRadioButton(Form)
self.radioButton.setObjectName(_fromUtf8("radioButton"))
self.gridLayout.addWidget(self.radioButton, 0, 1, 1, 1)
self.lineEdit = QtGui.QLineEdit(Form)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.gridLayout.addWidget(self.lineEdit, 1, 0, 1, 1)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.gridLayout.addWidget(self.pushButton, 1, 1, 1, 1)
self.listWidget = QtGui.QListWidget(Form)
self.listWidget.setEditTriggers(QtGui.QAbstractItemView.DoubleClicked|QtGui.QAbstractItemView.EditKeyPressed|QtGui.QAbstractItemView.SelectedClicked)
self.listWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems)
self.listWidget.setMovement(QtGui.QListView.Snap)
self.listWidget.setUniformItemSizes(False)
self.listWidget.setObjectName(_fromUtf8("listView"))
self.gridLayout.addWidget(self.listWidget, 2, 0, 1, 2)
#system tray
self.systemTrayIcon = QtGui.QSystemTrayIcon()
self.systemTrayIcon.setIcon(QtGui.QIcon(":/images/images/mad-icon.jpg"))
self.systemTrayIcon.setVisible(True)
self.systemTrayIcon.activated.connect(self.sysTrayIconActivated)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.radioButton.setText(_translate("Form", "monitor clipboard", None))
self.pushButton.setText(_translate("Form", "Add", None))
#when system tray icon is clicked, if window is visible, then hide. if it is not visible, then show
def sysTrayIconActivated(self, reason):
if reason == QtGui.QSystemTrayIcon.Trigger:
if Form.isHidden():
Form.show()
else:
Form.hide()
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 code should work
def changeEvent(self, event):
if event.type() == QEvent.WindowStateChange:
if event.oldState() and Qt.WindowMinimized:
print("WindowMinimized")
elif event.oldState() == Qt.WindowNoState or self.windowState() == Qt.WindowMaximized:
print("WindowMaximized")
You could use the changeEvent provided by QWidget:
def changeEvent(self, event):
if event.type() == QEvent.WindowStateChange:
if self.windowState() & Qt.WindowMinimized:
pass
I am currently working on a program to work with thermocouples that work with a Beagle Bone. The code is in python and when ran as a .py works fine, but my professor wants the program to have a GUI so the underclassmen have an easier time using the program.
import xlsxwriter
import Adafruit_BBIO.ADC as ADC
import time
ADC.setup()
workbook=xlsxwriter.Workbook('Volt.xlsx')
worksheet=workbook.add_worksheet()
row = 0
col=0
reading = 1
number = input("Enter number of measurements: ")
interv = input("Enter interval time: ")
while number > 0:
worksheet.write(row, col, reading)
fraction = ADC.read("AIN4")
fraction = ADC.read("AIN4")
volts = fraction * 1.8
print volts
worksheet.write(row, col + 1, volts)
time.sleep(interv)
number=number-1
row = row + 1
reading=reading+1
worksheet.write(row, 0, 'Reading Number')
worksheet.write(row, 1, 'Voltage')
workbook.close()
Now, how would I make it so when you press button 1 (on the code below) it runs?
Code for GUI:
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.setEnabled(True)
Form.resize(633, 378)
self.widget = QtGui.QWidget(Form)
self.widget.setGeometry(QtCore.QRect(10, 10, 611, 341))
self.widget.setObjectName(_fromUtf8("widget"))
self.gridLayout = QtGui.QGridLayout(self.widget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.pushButton_2 = QtGui.QPushButton(self.widget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.gridLayout.addWidget(self.pushButton_2, 2, 1, 1, 1)
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.gridLayout.addWidget(self.pushButton, 2, 0, 1, 1)
self.label = QtGui.QLabel(self.widget)
self.label.setAutoFillBackground(True)
self.label.setFrameShape(QtGui.QFrame.NoFrame)
self.label.setLineWidth(0)
self.label.setMidLineWidth(1)
self.label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label.setWordWrap(False)
self.label.setOpenExternalLinks(False)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.label_2 = QtGui.QLabel(self.widget)
self.label_2.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout.addWidget(self.label_2, 0, 1, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Beagle Bone Thermocouple Program- Coded by Joshua Baney", None))
self.pushButton_2.setText(_translate("Form", "Press for use of two thermocouples", None))
self.pushButton.setText(_translate("Form", "Press for use of one thermocouple", None))
self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600; text-decoration: underline;\">Beagle Bone thermocuple program</span></p></body></html>", None))
self.label_2.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt;\">Coded by Joshua Baney</span></p><p align=\"center\"><span style=\" font-size:9pt;\">support: joshnbaney#gmail.com</span></p><p align=\"center\"><span style=\" font-size:9pt;\"><br/></span></p><p align=\"center\"><span style=\" font-size:9pt;\"><br/></span></p></body></html>", 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_())
I suggest to use a new class that will initialize a GUI class:
from ui_Form import Ui_Form
class Widget(QWidget):
def __init__(self):
super(Widget, self).__init__(parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
# here you connect a button to
self.ui.pushButton_2.clicked.connect(self.run_code)
# execute the code you want
def run_code(self):
code.py # but better would be to create a method/function for this code or even a class with method to tun
So this is a short version of what I have but basically serving the same purpose:
import sys
from PyQt4 import QtGui, QtCore
def __init__(self):
super(PyQt, self).__init()
self.gridLayout = QtGui.QGridLayout()
self.setGeometry(200,200,200,200)
self.Enter = QtGui.QPushButton("Enter")
self.gridLayout.addWidget(self.Enter,1,0,0,0)
self.Enter.clicked.connect(self.buttonOK)
self.lineEdit = QtGui.QLineEdit()
self.gridLayout.addWidget(self.lineEdit,0,0,0,0)
def buttonOK(self):
# if statement checking if lineEdit.is_int() == False
question = QtGui.QMessageBox.question(self, "The value that you entered is not a whole number. Please enter again", QtGui.QMessageBox.OK | QtGui.QMessageBox.Ignore)
if question == QtGui.QMessageBox.OK
# Make the code wait for "Enter" button is pressed again
How would I go about making the code wait till the Enter button is pressed again, then make it run buttonOk again?
Add a bool to see if it has been pressed already. Something like this:
def __init__(self):
# ...
self.pushed = False
def buttonOK(self):
# if statement checking if lineEdit.is_int() == False
question = QtGui.QMessageBox.question(self, "The value that you entered is not a whole number. Please enter again", QtGui.QMessageBox.OK | QtGui.QMessageBox.Ignore)
if question == QtGui.QMessageBox.OK
if self.pushed = True:
# Second time it was pushed
else:
self.pushed = True
I suggest to use QDialog instead of QMessageBox. Try this:
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 MyAlert(QtGui.QDialog):
'''
This alert window used to display messages
and wait for user action to continue with the rest of the code
'''
text = ''
# type = 'warning' # used for image
def __init__(self, text, parent=None, *args, **kwargs):
super(MyAlert, self).__init__(parent)
self.text = text
# self.text = kwargs.pop('text', '')
self.setupUi()
def setupUi(self):
self.setObjectName(_fromUtf8("Dialog"))
self.resize(264, 130)
self.gridLayout = QtGui.QGridLayout(self)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.buttonBox = QtGui.QDialogButtonBox(self)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 1)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_2 = QtGui.QLabel(self)
self.label_2.setMaximumSize(QtCore.QSize(60, 16777215))
self.label_2.setText(_fromUtf8(""))
self.label_2.setPixmap(QtGui.QPixmap(_fromUtf8("../../Images/Icons/warning.png")))
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_2.addWidget(self.label_2)
self.label_3 = QtGui.QLabel(self)
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_2.addWidget(self.label_3)
self.gridLayout.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)
self.retranslateUi()
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), self.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), self.reject)
QtCore.QMetaObject.connectSlotsByName(self)
self.alert()
def retranslateUi(self):
self.setWindowTitle(_translate("Dialog", "Alert", None))
self.label_3.setText(_translate("Dialog", self.text, None))
def alert(self):
self.show()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
ui = MyAlert("test")
if(ui.exec_() == QtGui.QDialog.Accepted):
print 'ok'
else:
print 'NOT ok'
sys.exit(app.exec_())
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.