I want to run the function removeHi(self) only once in my program, how to accomplish this. Please advise me. My entire code below:
import sys
from PyQt5.QtWidgets import *
from functools import wraps
class TestWidget(QWidget):
gee = ''
def __init__(self):
global gee
gee = 'Hi'
QWidget.__init__(self, windowTitle="A Simple Example for PyQt.")
self.outputArea=QTextBrowser(self)
self.outputArea.append(gee)
self.helloButton=QPushButton("reply", self)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.outputArea)
self.layout().addWidget(self.helloButton)
self.helloButton.clicked.connect(self.removeHi)
self.helloButton.clicked.connect(self.sayHello)
def removeHi(self):
self.outputArea.clear()
def sayHello(self):
yourName, okay=QInputDialog.getText(self, "whats your name?", "name")
if not okay or yourName=="":
self.outputArea.append("hi stranger!")
else:
self.outputArea.append(f"hi,{yourName}")
app=QApplication(sys.argv)
testWidget=TestWidget()
testWidget.show()
sys.exit(app.exec_())
The GUI will show "Hi" when the program runs. I want the "Hi" in QTextBrowser removed after I push the button reply, but the program will clear everything in the text browser whenever I clicked the button.
My goal is: only the first Hi be removed, and the name from function sayHello(self) will remain whenever I push the reply button.
The problem resides in the logic of your program: you should check whether the text must be cleared or not, using a default value that would be changed whenever the dialog changes the output:
class TestWidget(QWidget):
clearHi = True
def __init__(self):
QWidget.__init__(self, windowTitle="A Simple Example for PyQt.")
self.outputArea = QTextBrowser()
self.outputArea.append('Hi')
self.helloButton = QPushButton("reply")
layout = QVBoxLayout(self)
layout.addWidget(self.outputArea)
layout.addWidget(self.helloButton)
self.helloButton.clicked.connect(self.removeHi)
self.helloButton.clicked.connect(self.sayHello)
def removeHi(self):
if self.clearHi:
self.outputArea.clear()
def sayHello(self):
yourName, okay = QInputDialog.getText(
self, "whats your name?", "name")
if not okay:
return
self.clearHi = False
if not yourName:
self.outputArea.append("hi stranger!")
else:
self.outputArea.append(f"hi, {yourName}")
Note: do not use globals.
Related
One post right before mine, I found some Code I would like to use. There is an ComboPopup which has checkboxes in it. If one of These checkboxes is activated, I want to pass the selected text back to my class (i.e. MyForm). There is an StaticText called self.text. I want to Change the Label with the choosen Text of the ComboPopup.
I tried it with:
test = MyForm()
MyForm.OnUpdate(test,item.GetText())
as I thought that self.text is parent from MyForm(). But that doesn't work. No errors, but also no changes of the text.
What is self in this case? Is there a good way to find out what self is ? Like print the Name or anything :-)
My Code:
import wx
import wx.stc
from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin
class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin):
def __init__(self, parent):
wx.ListCtrl.__init__(self, parent, wx.ID_ANY, style=wx.LC_REPORT |
wx.SUNKEN_BORDER)
CheckListCtrlMixin.__init__(self)
ListCtrlAutoWidthMixin.__init__(self)
self.SetSize(-1, -1, -1, 50)
def OnCheckItem(self, index, flag):
item = self.GetItem(index)
if flag:
what = "checked"
else:
what = "unchecked"
print(f'{item.GetText()} - {what}')
test = MyForm()
MyForm.OnUpdate(test,item.GetText())
class ListViewComboPopup(wx.ComboPopup):
def __init__(self):
wx.ComboPopup.__init__(self)
self.lc = None
def AddItem(self, txt):
self.lc.InsertItem(0, txt)
def Init(self):
self.value = -1
self.curitem = -1
def Create(self, parent):
self.lc = CheckListCtrl(parent)
self.lc.InsertColumn(0, '', width=90)
return True
def GetControl(self):
return self.lc
def OnPopup(self):
wx.ComboPopup.OnPopup(self)
def GetAdjustedSize(self, minWidth, prefHeight, maxHeight):
return wx.ComboPopup.GetAdjustedSize(
self, minWidth, 110, maxHeight)
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Popup Menu")
self.panel = wx.Panel(self)
vsizer = wx.BoxSizer(wx.VERTICAL)
comboCtrl = wx.ComboCtrl(self.panel, wx.ID_ANY, "Select Text")
popupCtrl = ListViewComboPopup()
comboCtrl.SetPopupControl(popupCtrl)
popupCtrl.AddItem("Text One")
self.txt = wx.StaticText(self.panel,-1,style = wx.ALIGN_LEFT)
self.txt.SetLabel("Startup Text")
vsizer.Add(comboCtrl,1,wx.EXPAND)
vsizer.Add(self.txt,1,wx.EXPAND)
self.panel.SetSizer(vsizer)
def OnUpdate(self, txt):
self.txt.SetLabel(txt)
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()
Your wx.Frame subclass instance does not have a parent. You explicitly create it without one:
wx.Frame.__init__(self, None, title="Popup Menu")
You create an instance of MyForm in your __name__ == '__main__' block:
frame = MyForm().Show()
# Note: your name 'frame' holds the return value of the method Show(), i.e. a boolean
# This probably should rather read:
# frame = MyForm()
# frame.Show()
This is the MyForm instance you show in your app.
What you do here:
test = MyForm()
is creating a new instance of MyFrame (that has nothing to do with the one your app shows). You then call onUpdate on that new instance of your MyForm class
MyForm.OnUpdate(test,item.GetText())
Since you never Show() that new instance, you can't see the effect of your operation. However, you probably don't want/need that new instance anyway.
You need your instance from the main block.
There is a parent argument on the CheckListCtrl initializer. This might contain a chain of objects which you probably can ascend until you reach your MyForm instance.
I can't tell for sure, since it is not visible where and how this is called in the ListViewComboPopup:
def Create(self, parent):
self.lc = CheckListCtrl(parent)
Do a print(self.Parent) in OnCheckItem to see what it contains and then add another .Parent to self.Parent until you hopefully end up on a <__main__.MyForm instance [...]>. This is where you want to call the onUpdate Method. That should look similar to this:
self.Parent.Parent.Parent.OnUpdate(item.GetText())
# the number of '.Parent' my vary, based on where in the chain you find your MyForm instance
Edit
As per the OP's comment, the parent attribute on wx objects is spelled with a capital P. The respective code snippets have been updated accordingly.
I don't know what wx library does but there is a way to check where .text is.
You want vars() mixed with pprint():
from pprint import pprint
pprint(vars(your_object))
pprint(your_object) # this is OK too
Suggestion 2
type(x).__name__
This gets you the class name of an instance. You could insert this line before self.text. And give self as argument instead of x.
Original: Link
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
Uh, okay, friends, now I'm trying to add "export to Excel" feature for every table in my app like this:
...
def update_exportable_tables(self, *window):
"""
Please don't ask why, here 'I know what I'm doing'
"""
if not window:
window = self.window
for obj in window.__dict__:
objname = obj.title().lower()
the_object_itself = window.__dict__[obj]
if isinstance(the_object_itself, (QTableWidget, QTableView)):
the_object_itself.setContextMenuPolicy(Qt.CustomContextMenu)
the_object_itself.customContextMenuRequested.connect(self.TableContextEvent)
def TableContextEvent(self, event):
menu = QMenu()
excelAction = menu.addAction(u"Export to Excel")
excelAction.triggered.connect(self.export)
action = menu.exec_(QCursor.pos())
def export(self):
print 'Here I should do export'
...
Yeah, it works fine, but.... The question is how should I pass the clicked table instance to my export() function?
There are several different ways to solve this. Here's one way:
def update_exportable_tables(self):
for widget in QtGui.qApp.allWidgets():
if isinstance(widget, QTableView):
widget.setContextMenuPolicy(Qt.CustomContextMenu)
widget.customContextMenuRequested.connect(self.showContextMenu)
def showContextMenu(self, pos):
table = self.sender()
pos = table.viewport().mapToGlobal(pos)
menu = QtGui.QMenu()
excelAction = menu.addAction("Export to Excel")
if menu.exec_(pos) is excelAction:
self.export(table)
def export(self, table):
print 'Here I should do export:', table
(NB: QTableWidget is a subclass of QTableView).
Okay, thanks to Eli Bendersky, I googled one way to do it.
if isinstance(the_object_itself, (QTableWidget, QTableView)):
the_object_itself.setContextMenuPolicy(Qt.CustomContextMenu)
tricky = lambda: self.TableContextEvent(the_object_itself)
the_object_itself.customContextMenuRequested.connect(tricky)
...
def TableContextEvent(self, table_instance):
print table_instance
# ^^^^^^^^^^^^^ And yes, we have it!
upd1: It's still wrong, due connecting to only one instance (only last table instance is passed everywhere)
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)
...
i'm creating a dialog that finds out what is focused element.
that's what i wrote:
import gtk
import gobject
class FocusedElementPath(gtk.Dialog):
def __init__(self, parent, title=None):
gtk.Dialog.__init__(self, title or 'Show path', parent)
self.catch_within = parent
self.catch_focus = True
self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
again_btn = gtk.Button('',gtk.STOCK_REFRESH)
again_btn.connect('activate', self.refresh_pressed)
again_btn.show()
self.action_area.add(again_btn)
self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
self.action_area.set_layout(gtk.BUTTONBOX_EDGE)
self.path = gtk.Label()
self.path.show()
self.vbox.add(self.path)
def refresh_pressed(self, btn):
self.catch_focus = True
def do_focus_out_event(self, evt):
nl = self.catch_within.get_focus()
if nl:
self.catch_within.activate_focus()
self.path.set_text(repr(nl))
else:
self.path.set_text('None')
gtk.Dialog.on_focus_event(self, evt)
gobject.type_register(FocusedElementPath)
the problem is it returns previously focused element.
is there any way to find out currently focused element?
i've tried different events (for dialog and for window), but nothing helped :(
what am i doing wrong or how do i do this correctly?
gtk.Window.get_focus (also available in gtk.Dialog) will return the currently focused child.
Anyway I don't quite understand what you want to achieve here...