How to Add Items to QComboBox from another class PyQT? - python

I'm designing this thing on Qt Designer using PyQt. So I have a QMainWindow from where the user can open a QDialog to Input some data I'm saving in a Json file (AddUser function below)
What I want is when the AddUser push button is clicked, from the AddUser function, How can I Add a new Item in a Combobox that is defined in the MainWindow Class ?
Here is the code of the two classes
import ui.mainwindow as MnWindow
import ui.AddUserDialog as AddUserDialog
#First GUI
class MainWindow(QMainWindow,MnWindow.Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
#Second GUI
class AddUserDialog(QDialog,AddUserDialog.Ui_Dialog):
def __init__(self,parent=None):
super(AddUserDialog,self).__init__(parent)
self.setupUi(self)
self.pushButtonAddUser.clicked.connect(self.AddUser)
def AddUser(self):
DateDeNaissance = self.dateEditDateDeNaissance.date().toString(Qt.ISODate)
DateDeSortie = self.dateEditDateDeSortie.date().toString(Qt.ISODate)
new_user = {
'firstname' : self.lineEditPrenom.text(),
'lastname' : self.lineEditNom.text(),
'DateDeNaissance' : DateDeNaissance[-2:] + DateDeNaissance[5:7] + DateDeNaissance[:4],
'LieuDeNaissance' : self.lineEditLieuNaissance.text(),
'Adresse' : self.lineEditAdresse.text(),
'Ville' : self.lineEditVille.text(),
'CodePostal' : self.lineEditCodePostal.text(),
'DateDeSortie' : DateDeSortie[-2:] + DateDeSortie[5:7] + DateDeSortie[:4],
'Heure' : str(self.timeEditSortie.time().hour()),
}
with open('TestJson.json','r') as f:
data = json.load(f)
data['users'].append(new_user)
with open('TestJson.json','w') as f:
json.dump(data,f,indent=3)
MainWindow.UserComboBox.addItem(new_user['firstname'] + ' ' + new_user['lastname'])
The last line the incorrect of course, How can I do that properly ?
PS: I've read that I need to inherit from MainWindow Class, but I've been trying that with no success.

There are two possible ways to do so.
The simplest way is to access to the properties (or properties of widgets) from the reference to the instance.
class MainWindow(QMainWindow,MnWindow.Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.someButton.clicked.connect(self.addUser)
def addUser(self):
dialog = AddUserDialog(self)
if dialog.exec_():
firstname = dialog.lineEditPrenom.text()
lastname = dialog.lineEditNom.text()
self.UserComboBox.addItem('{} {}'.format(firstname, lastname))
Alternatively, you can overwrite the exec_() method of the dialog and return the values if the dialog is accepted:
class MainWindow(QMainWindow,MnWindow.Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.addUserButton.clicked.connect(self.addUser)
def addUser(self):
res = AddUserDialog(self).exec_()
if res:
self.UserComboBox.addItem(res)
class AddUserDialog(QDialog,AddUserDialog.Ui_Dialog):
def exec_(self):
if super().exec_():
firstname = self.lineEditPrenom.text()
lastname = self.lineEditNom.text()
return '{} {}'.format(firstname, lastname)
Both solutions work with the assumption that the user is accepting the dialog, which normally happens by pressing an "Ok" button. If you want to use a custom button, you should also call self.accept() at the end of the AddUser() function.
Consider that Qt provides the QDialogButtonBox for this purpose, and you don't need to add your own buttons. I believe you're probably using a QPushButton because the default buttons of QDialogButtonBox have fixed labels and none of them has the "Add" text, but those buttons can be renamed as you wish. Assuming you have a QDialogButtonBox on your dialog named buttonBox (the default for dialogs with buttons) with an "Ok" button, you can implement the json writing directly in the accept() function:
class AddUserDialog(QDialog,AddUserDialog.Ui_Dialog):
def __init__(self,parent=None):
super(AddUserDialog,self).__init__(parent)
self.setupUi(self)
self.buttonBox.button(self.buttonBox.Ok).setText('Add user')
def accept(self):
DateDeNaissance = self.dateEditDateDeNaissance.date().toString(Qt.ISODate)
DateDeSortie = self.dateEditDateDeSortie.date().toString(Qt.ISODate)
new_user = {
'firstname' : self.lineEditPrenom.text(),
'lastname' : self.lineEditNom.text(),
'DateDeNaissance' : DateDeNaissance[-2:] + DateDeNaissance[5:7] + DateDeNaissance[:4],
'LieuDeNaissance' : self.lineEditLieuNaissance.text(),
'Adresse' : self.lineEditAdresse.text(),
'Ville' : self.lineEditVille.text(),
'CodePostal' : self.lineEditCodePostal.text(),
'DateDeSortie' : DateDeSortie[-2:] + DateDeSortie[5:7] + DateDeSortie[:4],
'Heure' : str(self.timeEditSortie.time().hour()),
}
with open('TestJson.json','r') as f:
data = json.load(f)
data['users'].append(new_user)
with open('TestJson.json','w') as f:
json.dump(data,f,indent=3)
super().accept()
Note that Designer automatically connects the accepted and rejected signals of the button box to the relative accept and reject slots of the dialog. If you don't want to rebuild the whole GUI and still add a button box, just create a new dialog with buttons and ctrl-drag the buttonbox to your existing interface, but you have to recreate the connections manually; you can do that using the signal/slot edit mode of Designer (Edit menu -> Edit Signals/Slots, or F4) or within your code:
class AddUserDialog(QDialog,AddUserDialog.Ui_Dialog):
def __init__(self,parent=None):
super(AddUserDialog,self).__init__(parent)
self.setupUi(self)
self.buttonBox.button(self.buttonBox.Ok).setText('Add user')
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
# ...

You can pass the combo box as an argument when you create an instance of AddUserDialog:
class AddUserDialog(QDialog,AddUserDialog.Ui_Dialog):
def __init__(self,parent=None, combobox= None):
super(AddUserDialog,self).__init__(parent)
self.setupUi(self)
self.combobox = combobox
And in AddUser method, use self.combobox:
# MainWindow.UserComboBox.addItem(new_user['firstname'] + ' ' + new_user['lastname'])
self.combobox.addItem(new_user['firstname'] + ' ' + new_user['lastname'])
Alternatively, you already know the parent of the dialog when you make an instance. I think the super(AddUserDialog,self).__init__(parent) line will set self.parent for the dialog. Then in AddUser method, use this statement:
self.parent.UserComboBox..addItem(new_user['firstname'] + ' ' + new_user['lastname'])

Related

Access sub interface values in the same function

I had two classes - main and sub interface
There is a pushbutton which will calls out the sub interface and I am trying to get the output of the sub tool interface directly (or almost immediately) so that it can be use within the push button function.
In my code, if I did the following:
hit on 'Click Me'
checked 2 options and hit the 'Apply to selected item' in the sub interface
the print line of 'my dict values' is still empty
Unless I create another function get_results in which then self.my_dict will be shown correctly.
As such, how can I code it in a way that once the 'Apply...' button is hit, self.my_dict will be updated without the need of creating another function? Or am I just overthinking things?
class SubMenuWindow(QtGui.QWidget):
def __init__(self, menu_items, parent=None):
super(SubMenuWindow, self).__init__(parent)
self.my_lyt = QtGui.QVBoxLayout()
self.checked_options = []
self.sel = {}
for menu_name, submenu_name in menu_items.items():
# Set the main menu item name
self.groupbox = QtGui.QGroupBox(self)
self.groupbox.setTitle(menu_name)
self.groupbox.setLayout(QtGui.QVBoxLayout())
self.my_lyt.addWidget(self.groupbox)
if submenu_name:
sub_txt = [action for action in submenu_name]
for s in sub_txt:
sub_chk = QtGui.QCheckBox(s)
self.checked_options.append(sub_chk)
self.groupbox.layout().addWidget(sub_chk)
apply_tag_btn = QtGui.QPushButton('Apply to selected item')
apply_tag_btn.clicked.connect(self.get_checked_options)
self.my_lyt.addWidget(apply_tag_btn)
self.my_lyt.addStretch()
self.setLayout(self.my_lyt)
self.show()
def get_checked_options(self):
for f in self.checked_options:
if f.isChecked():
self.sel[f.parent().title()] = f.text()
class MainWin(QtGui.QWidget):
def __init__(self, parent=None):
super(MainWin, self).__init__(parent)
self.my_dict = {}
btnA = QtGui.QPushButton('Click Me')
btnA.clicked.connect(self.get_options)
btnB = QtGui.QPushButton('Get results')
btnB.clicked.connect(self.get_results)
layout = QtGui.QVBoxLayout()
layout.addWidget(btnA)
layout.addWidget(btnB)
self.setLayout(layout)
def get_options(self):
sample_dict = {'GrpA' : ['John', 'Zack'], 'GrpB' : ['Alice', 'Phan']}
self.subWin = SubMenuWindow(sample_dict)
# I had want to get the values from subWin as soon as User has hit on
# the 'Apply to selected item' button
self.my_dict = self.subWin.sel
print ">>> my dict values : ", self.my_dict
# do something else from here thereafter...
def get_results(self):
print self.subWin.sel
Creating the new window will not block, so your print statements will be executed before the user has anything selected. You could pass in a callback to notify the calling widget when the user changes the selection.
for example:
class SubMenuWindow(QtWidgets.QWidget):
def __init__(self, menu_items, parent=None, callback=None):
super(SubMenuWindow, self).__init__(parent)
self.callback = callback
[...]
def get_checked_options(self):
for f in self.checked_options:
if f.isChecked():
self.sel[f.parent().title()] = f.text()
if self.callback:
self.callback()
and pass in the callback:
def get_options(self):
sample_dict = {'GrpA' : ['John', 'Zack'], 'GrpB' : ['Alice', 'Phan']}
self.subWin = SubMenuWindow(sample_dict, callback=self.get_results)
[...]
this way your get_result method will be called whenever the user clicks the apply button in the SubMenuWindow.

How to connect QTreeWidget and QStackedWidget in PyQt4?

I'm sorry but just a beginner of Python.
I just want to change index of QStackedWidget by the item click of QTreeWidget. I searched for the tutorials of SIGNAL and SLOT online, but just cannot solve the problem.
The parameters in QTreeWidget signal and QStackedWidget slot are not fitted.
self.connect(qtree, QtCore.SIGNAL("itemClicked(QTreeWidgetItem*,int)"), stack, QtCore.SLOT("setCurrentIndex(int)"))
And I tried this:
qtree.itemClicked.connect(stack.setCurrentIndex)
It just showed the error:
TypeError: setCurrentIndex(self, int): argument 1 has unexpected type 'QTreeWidgetItem'
I think there may be a method, but I cannot find on the network.
Like this:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class StockDialog(QDialog):
def __init__(self,parent=None):
super(StockDialog,self).__init__(parent)
mainSplitter=QSplitter(Qt.Horizontal)
treewidget = QTreeWidget(mainSplitter)
treewidget.setHeaderLabels(["Tree"])
treeroot = QTreeWidgetItem(treewidget, ["Stack"])
treeitem1 = QTreeWidgetItem(["WorkSpace"])
treeitem2 = QTreeWidgetItem(["About"])
treeroot.addChild(treeitem1)
treeroot.addChild(treeitem2)
stack=QStackedWidget(mainSplitter)
stack.setFrameStyle(QFrame.Panel|QFrame.Raised)
stackworkspace=StackWorkSpace()
stackabout=StackAbout()
stack.addWidget(stackworkspace)
stack.addWidget(stackabout)
closePushButton=QPushButton(self.tr("Close"))
self.connect(treewidget,
SIGNAL("itemClicked(int)"),
stack,SLOT("setCurrentIndex(int)"))
self.connect(closePushButton,
SIGNAL("clicked()"),
self,SLOT("close()"))
layout=QVBoxLayout(self)
layout.addWidget(mainSplitter)
layout.addWidget(closePushButton)
self.setLayout(layout)
class StackWorkSpace(QWidget):
def __init__(self,parent=None):
super(StackWorkSpace,self).__init__(parent)
widget1=QTextEdit(self.tr("WorkSpace"))
widget2=QTextEdit(self.tr("WorkSpace"))
layout=QGridLayout(self)
layout.addWidget(widget1,0,0)
layout.addWidget(widget2,0,1)
class StackAbout(QDialog):
def __init__(self,parent=None):
super(StackAbout,self).__init__(parent)
self.setStyleSheet("background: red")
app=QApplication(sys.argv)
main=StockDialog()
main.show()
app.exec_()
When change the QTreeWidget to the QListWidget in StockDialog class, it works.
class StockDialog(QDialog):
def __init__(self,parent=None):
super(StockDialog,self).__init__(parent)
mainSplitter=QSplitter(Qt.Horizontal)
listwidget=QListWidget(mainSplitter)
listwidget.insertItem(0,self.tr("WorkSpace"))
listwidget.insertItem(1,self.tr("About"))
stack=QStackedWidget(mainSplitter)
stack.setFrameStyle(QFrame.Panel|QFrame.Raised)
stackworkspace=StackWorkSpace()
stackabout=StackAbout()
stack.addWidget(stackworkspace)
stack.addWidget(stackabout)
closePushButton=QPushButton(self.tr("Close"))
self.connect(listwidget,
SIGNAL("currentRowChanged(int)"),
stack,SLOT("setCurrentIndex(int)"))
self.connect(closePushButton,
SIGNAL("clicked()"),
self,SLOT("close()"))
layout=QVBoxLayout(self)
layout.addWidget(mainSplitter)
layout.addWidget(closePushButton)
self.setLayout(layout)
Now, I want to do this with QTreeWidget, how can I do?
The strategy to solve this problem is to save the index information associated with each widget in the QTreeWidgetItem. QTreeWidgetItem has the setData() method that allows us to save information in the item and in this case we will save the index. The index is returned every time you add a widget to QStackedWidget through addWidget(), so in summary we will do the following:
treeitem1.setData(0, Qt.UserRole, stack.addWidget(stackworkspace))
treeitem2.setData(0, Qt.UserRole, stack.addWidget(stackabout))
After connecting the itemClicked signal of QTreeWidget, this returns the column and the item pressed, with this information we obtain the QStackedWidget index for it we recover the data saved through the function data():
treewidget.itemClicked.connect(lambda item, column: stack.setCurrentIndex(item.data(column, Qt.UserRole))
if item.data(column, Qt.UserRole) is not None else None)
The necessary code can be found in the following section:
class StockDialog(QDialog):
def __init__(self, parent=None):
super(StockDialog, self).__init__(parent)
mainSplitter = QSplitter(Qt.Horizontal)
treewidget = QTreeWidget(mainSplitter)
treewidget.setHeaderLabels(["Tree"])
treeroot = QTreeWidgetItem(treewidget, ["Stack"])
treeitem1 = QTreeWidgetItem(["WorkSpace"])
treeitem2 = QTreeWidgetItem(["About"])
treeroot.addChild(treeitem1)
treeroot.addChild(treeitem2)
stack = QStackedWidget(mainSplitter)
stack.setFrameStyle(QFrame.Panel | QFrame.Raised)
stackworkspace = StackWorkSpace()
stackabout = StackAbout()
treeitem1.setData(0, Qt.UserRole, stack.addWidget(stackworkspace))
treeitem2.setData(0, Qt.UserRole, stack.addWidget(stackabout))
closePushButton = QPushButton(self.tr("Close"))
treewidget.itemClicked.connect(lambda item, column: stack.setCurrentIndex(item.data(column, Qt.UserRole))
if item.data(column, Qt.UserRole) is not None else None)
layout = QVBoxLayout(self)
layout.addWidget(mainSplitter)
layout.addWidget(closePushButton)
self.setLayout(layout)

lazy Filtering QTreeview with QsortFIlterProxymodel

I want to extend a question I asked earlier with a filter. In my previous question
I got help in lazy loading the treeview, parents first and only adding the parent's children when the user clicks on the node more or less as follows
from PyQt4 import QtGui
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.mytreeview = QtGui.QTreeView(self)
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.mytreeview)
self.model = QtGui.QStandardItemModel(self.mytreeview)
self.mytreeview.setModel(self.model)
self.mytreeview.clicked.connect(self.update_model)
self.initialise_model()
def initialise_model(self):
for text in ["parent1", "parent2", "parent3"]:
item = QtGui.QStandardItem(text)
self.model.appendRow(item)
def update_model(self, index):
parent = self.model.itemFromIndex(index)
for text in ["children1", "children2", "children3"]:
children = QtGui.QStandardItem("{}_{}".format(parent.text(), text))
parent.appendRow(children)
self.mytreeview.expand(index)
I now want to extend and make use of a filter for the treeview, so that a user can type in the name of a parent node and the treeview will filter itself down to the appropriate relevant nodes. I still want to keep the ability for the user to click on a parent node and even when filtered only then would the child nodes be added to the parent.
How can i adapt the following to do so? I have set the treeview up as follows
proxyModel = QSortFilterProxyModel(treeView)
proxyModel.setSourceModel(self.model)
# set model
treeView.setModel(proxyModel);
treeView.setSortingEnabled(true)
def update_model(self, index):
parent = self.model.itemFromIndex(index)
##not sure about this now in the light of the proxyModel
for text in ["children1", "children2", "children3"]:
children = QtGui.QStandardItem("{}_{}".format(parent.text(), text))
parent.appendRow(children)
self.mytreeview.expand(index)#not sure about this either as the index is of the proxyModel
I have two main questions firstly the proxyModel Index and the source model index, I am not sure how this works and also when expanding the clicked on node,
The classes that inherit from QAbstractProxyModel as QSortFilterProxyModel have the mapToSource() method that returns the index of the source model passing the index of the proxy model, also has another method called mapFromSource() that does the inverse so you must use that method to be able to add the items to the correct model.
To filter the data I added a QLineEdit where the textChanged signal is connected, the text that provides the signal we used for the filter.
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.filterLe = QtGui.QLineEdit(self)
self.mytreeview = QtGui.QTreeView(self)
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.filterLe)
self.layout().addWidget(self.mytreeview)
self.model = QtGui.QStandardItemModel(self.mytreeview)
self.proxyModel = QtGui.QSortFilterProxyModel(self.mytreeview)
self.proxyModel.setSourceModel(self.model)
self.mytreeview.setSortingEnabled(True)
# set model
self.mytreeview.setModel(self.proxyModel)
self.mytreeview.clicked.connect(self.update_model)
self.filterLe.textChanged.connect(self.onTextChanged)
self.initialise_model()
#QtCore.pyqtSlot(str)
def onTextChanged(self, text):
self.proxyModel.setFilterRegExp(text)
def initialise_model(self):
for text in ["parent1", "parent2", "parent3"]:
item = QtGui.QStandardItem(text)
self.model.appendRow(item)
def update_model(self, index):
ix = self.proxyModel.mapToSource(index)
parent = self.model.itemFromIndex(ix)
for text in ["children1", "children2", "children3"]:
children = QtGui.QStandardItem("{}_{}".format(parent.text(), text))
parent.appendRow(children)
self.mytreeview.expand(index)

PyQt Get specific value in ListWidget

I am new to python and pyqt/pyside ...
i make customwidget class consist of 2 label (title & desc) which is example instance to add to Listwidget later ...
here is the complete clean code (pyside maya)
import PySide.QtCore as qc
import PySide.QtGui as qg
class CustomQWidget (qg.QWidget):
def __init__ (self, parent = None):
super(CustomQWidget, self).__init__(parent)
self.textQVBoxLayout = qg.QVBoxLayout()
self.titleLabel = qg.QLabel()
self.description = qg.QLabel()
self.textQVBoxLayout.addWidget(self.titleLabel)
self.textQVBoxLayout.addWidget(self.description)
self.setLayout(self.textQVBoxLayout)
def setTitle (self, text):
self.titleLabel.setText(text)
def setDescription (self, text):
self.description.setText(text)
class example_ui(qg.QDialog):
def __init__(self):
qg.QDialog.__init__(self)
self.myQListWidget = qg.QListWidget(self)
self.myQListWidget.currentItemChanged.connect(self.getTitleValue)
self.myQListWidget.setGeometry(qc.QRect(0,0,200,300))
# make instance customwidget item (just one)------
instance_1 = CustomQWidget()
instance_1.setTitle('First title')
instance_1.setDescription('this is a sample desc')
myQListWidgetItem = qg.QListWidgetItem(self.myQListWidget)
myQListWidgetItem.setSizeHint(instance_1.sizeHint())
self.myQListWidget.addItem(myQListWidgetItem)
self.myQListWidget.setItemWidget(myQListWidgetItem, instance_1)
def getTitleValue(self,val):
# i make assume something like below but didnt work
# print (self.myQListWidget.currentItem.titleLabel.text()
return 0
dialog = example_ui()
dialog.show()
now at getTitleValue function how do i get Title and desc value when i change selection ?
You should remember that the list items and corresponding widgets are not the same. Luckily, QListWidget tracks them and gives you access to the displayed widget if you provide the list item:
class example_ui(qg.QDialog):
def getTitleValue(self,val):
# parameter val is actually the same as self.myQListWidget.currentItem
selected_widget = self.myQListWidget.itemWidget(val)
print selected_widget.titleLabel.text()
return 0
Side note: I had to add a main loop in order for the app to be executed at all:
import sys # to give Qt access to parameters
# ... class definitions etc. ...
app = qg.QApplication(sys.argv)
dialog = example_ui()
dialog.show()
exec_status = app.exec_() # main loop

PyQt4 QDialog connections not being made

I am working on an application using PyQt4 and the designer it provides. I have a main window application that works fine, but I wanted to create custom message dialogs. I designed a dialog and set up some custom signal/slot connections in the __init__ method and wrote an if __name__=='__main__': and had a test. The custom slots work fine. However, when I create an instance of my dialog from my main window application, none of the buttons work. Here is my dialog:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import encode_dialog_ui
# Ui_EncodeDialog is the python class generated by pyuic4 from the Designer
class EncodeDialog(encode_dialog_ui.Ui_EncodeDialog):
def __init__(self, parent, in_org_im, txt_file, in_enc_im):
self.qd = QDialog(parent)
self.setupUi(self.qd)
self.qd.show()
self.message = (txt_file.split("/")[-1] + " encoded into " +
in_org_im.split("/")[-1] + " and written to " +
in_enc_im.split("/")[-1] + ".")
QObject.connect(self.view_image_button, SIGNAL("clicked()"),
self.on_view_image_button_press)
self.org_im = in_org_im
self.enc_im = in_enc_im
self.encoded_label.setText(self.message)
def on_view_image_button_press(self):
print "hello world"
if __name__ == '__main__':
app = QApplication(sys.argv)
tmp = QMainWindow()
myg = EncodeDialog(tmp,'flower2.png','b','flower.png')
app.exec_()
If I run this class it works fine, and pressing the view_image_button prints hello world to the console. However when I use the call
#self.mw is a QMainWindow, the rest are strings
EncodeDialog(self.mw, self.encode_image_filename,
self.encode_txt_filename,
self.encode_new_image_filename)
in my main window class, the dialog displays correctly but the view_image_button does nothing when clicked. I have googled for a solution, but couldn't find anything useful. Let me know if you need any more information. Any help on this would be appreciated!
As requested below is some more code from my main window class for brevity's sake I have added ellipses to remove code that seemed irrelevant. If no one can think of anything still, I will add more. (If indenting is a little off, it happened in copy-pasting. The orignal code is correct)
class MyGUI(MainWindow.Ui_MainWindow):
def __init__(self):
self.mw = QMainWindow()
self.setupUi(self.mw)
self.mw.show()
self.encode_red_bits = 1
self.encode_blue_bits = 1
self.encode_green_bits = 1
self.decode_red_bits = 1
self.decode_blue_bits = 1
self.decode_green_bits = 1
self.encode_image_filename = ""
self.encode_new_image_filename = ""
self.encode_txt_filename = ""
self.decode_image_filename = ""
self.decode_txt_filename = ""
# Encode events
...
QObject.connect(self.encode_button, SIGNAL("clicked()"),
self.on_encode_button_press)
# Decode events
...
# Encode event handlers
...
def on_encode_button_press(self):
tmp = QErrorMessage(self.mw)
if (self.encode_image_filename != "" and
self.encode_new_image_filename != "" and
self.encode_txt_filename != ""):
try:
im = Steganography.encode(self.encode_image_filename, self.encode_txt_filename,
self.encode_red_bits, self.encode_green_bits,
self.encode_blue_bits)
im.save(self.encode_new_image_filename)
encode_dialog.EncodeDialog(self.mw, self.encode_image_filename,
self.encode_txt_filename,
self.encode_new_image_filename)
except Steganography.FileTooLargeException:
tmp.showMessage(self.encode_txt_filename.split("/")[-1] +
" is to large to be encoded into " +
self.encode_image_filename.split("/")[-1])
else:
tmp.showMessage("Please specify all filenames.")
# Decode event handlers
...
if __name__ == '__main__':
app = QApplication(sys.argv)
myg = MyGUI()
app.exec_()
It feels like the signal is just not getting passed from the parent down to your child QDIalog.
Try these suggestions:
Use the new method for connecting signals
Instead of extending the classes pyuic created, extend the actual QT classes and call the ones generated by pyuic
Your new code will look something like this:
class MyGUI(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.mw = MainWindow.Ui_MainWindow()
self.mw.setupUi(self)
self.mw.show()
...
self.encode_button.clicked.connect(self.on_encode_button_press)
...
class EncodeDialog(QDialog):
def __init__(self, parent, in_org_im, txt_file, in_enc_im):
QDialog.__init__(self, parent)
self.qd = encode_dialog_ui.Ui_EncodeDialog()
self.qd.setupUi(self)
self.qd.show()
...
self.view_image_button.clicked.connect(self.on_view_image_button_press)
...

Categories

Resources