wxPython: Initialize class for the main window - input

I am trying to disable the interface from re-sizing, note that the interface has lots of widgets and panels already.
To my understanding, I can disable re-sizing with the following line of code:
wx.Frame(parent, style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)
However, I have created the code based on the following format:
def main():
ex = wx.App()
MainWindow(None)
ex.MainLoop()
class MainWindow(wx.Frame):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
...
How should I edit the code to mention that re-sizing is not allowed?

It looks like you should be able to just replace one line of code:
#was: MainWindow(None)
MainWindow(None, style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)

Related

PyQt5 top row of QFormLayout not responding to mouse click

Using QtDesigner and PyQt5 with pyuic5 I'm setting up a FormLayout with a variable number of rows.
Each row is a custom widget created in QtDesigner, consisting of a QLabel and a QHBoxLayout containing a QLineEdit and QPushButton.
I create the row UI using
def get_data_widget(parent=None, **kwargs):
widget = QtWidgets.QWidget(parent)
dlg_ui = wgtDataRow.Ui_Form() # from the custom made widget
dlg_ui.setupUi(widget)
# recursively ensure all objectName()s are unique
rename_widget(widget, "_%s" % unique_id())
dlg_ui.label.setText(kwargs.get('name') or '')
dlg_ui.editData.setText(kwargs.get('value') or '')
return dlg_ui
The row UI is inserted in the QFormLayout in a QDialog method:
def add_data_entry_row(self, name, **kwargs):
# simplified code, but this is the bit that affects the QFormLayout
posn = kwargs.get('position', 0)
data_ui = get_data_widget(self, name=name, value=kwargs.get('value'))
self.dlg_ui.formLayout.insertRow(posn, data_ui.label, data_ui.widget)
The problem I have is that the first row of the QFormLayout is not responding to the mouse clicks.
If I insert a new row at 0 the previously unresponsive row is moved down and becomes responsive and the new (top) row unresponsive.
Can anyone throw any light on this?
While trying to generate a minimal example which had the same problem I found the cause. Basically I was making changes to the UI before executing show()
What I had (code minimised for clarity)
class Dialog(QtWidgets.QDialog):
def __init__(self, **kwargs):
super().__init__()
self.dlg_ui = Ui_Dialog()
self.dlg_ui.setupUi(self)
self.setModal(True)
self.init_ui(**kwargs) # load the UI widgets with data
self.show()
which should have been
class Dialog(QtWidgets.QDialog):
def __init__(self, **kwargs):
super().__init__()
self.dlg_ui = Ui_Dialog()
self.dlg_ui.setupUi(self)
self.setModal(True)
self.show() # excute BEFORE loading the UI
self.init_ui(**kwargs) # load the UI widgets with data

Update ListView dynamically when Log file updated

I have a log file in .txt format, that is being updated continuously. Then I want to show the file content in ListView (PyQt5) dynamically
Use a QFileSystemWatcher to detect when you file has been modified.
A quick example:
class LogWatcher(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self.watcher = QFileSystemWatcher()
self.watcher.addPath("./foobar.txt") # The file you want to check
self.watcher.fileChanged.connect(self.displayLine)
def displayLine(self, path): # Will be called when the file has changed
print(path, "has changed")
if __name__ == '__main__':
app = QtWidgets.QApplication([])
logger = LogWatcher()
sys.exit(app.exec_())
Each time the file foobar.txt changes, the method displayLine is called

Confusion in JTextField () of jython in sikuli

This is my code :-
from javax.swing import *
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
panel = JPanel()
panel.setLayout(None)
self.getContentPane().add(panel)
panel.setLayout(None)
area = JTextField('',15)
panel.add(JLabel("username:", SwingConstants.RIGHT))
panel.add(area)
self.setTitle("Quit button")
self.setSize(600, 400)
self.setLocationRelativeTo(None)
self.setVisible(True)
def onQuit(self, e):
System.exit(0)
if __name__ == '__main__':
Example()
Here I am just trying to make of use JTextField() so that I can get some input from the user. But after running it, the window was blank, there was no text field on the window. I ran it in sikuli r930 on windows 7. Could anyone tell me what has gone wrong??
I think there is a problem with layout in your code. Try to set some layout instead of "None". Fixed initUI function could look like this:
def initUI(self):
panel = JPanel()
panel.setLayout(FlowLayout(FlowLayout.CENTER,1,150))
self.getContentPane().add(panel)
area = JTextField('',15)
panel.add(JLabel("username:", SwingConstants.RIGHT))
panel.add(area)
self.setTitle("Quit button")
self.setSize(600, 400)
self.setLocationRelativeTo(None)
self.setVisible(True)
Additional import line is needed in this case:
from java.awt import FlowLayout

Celery: abort task on connection error

I have to implement a Task subclass that gracefully fails if the broker is not running - currently I'm using RabbitMQ.
I could probably just use a try statement to catch the exception:
try:
Mytask.delay(arg1, arg2)
except socket.error:
# Send an notice to an admin
pass
but I'd like to create a subclass of Task that can handle that.
I've tried something like that:
class MyTask(Task):
ignore_result = True
def __call__(self, *args, **kwargs):
try:
return self.run(*args, **kwargs)
except socket.error:
# Send an notice to an admin
return None
but the workflow is clearly wrong. I think I need to inject maybe a backend subclass or a failure policy somehow.
Do you have any suggestion?
A possible solution I came up with:
import socket
from celery.decorators import task
from celery.task import Task
from celery.backends.base import BaseBackend
UNDELIVERED = 'UNDELIVERED'
class DummyBackend(BaseBackend):
"""
Dummy queue backend for undelivered messages (due to the broker being down).
"""
def store_result(self, *args, **kwargs):
pass
def get_status(self, *args, **kwargs):
return UNDELIVERED
def _dummy(self, *args, **kwargs):
return None
wait_for = get_result = get_traceback = _dummy
class SafeTask(Task):
"""
A task not raising socket errors if the broker is down.
"""
abstract = True
on_broker_error = None
errbackend = DummyBackend
#classmethod
def apply_async(cls, *args, **kwargs):
try:
return super(SafeTask, cls).apply_async(*args, **kwargs)
except socket.error, err:
if cls.on_broker_error is not None:
cls.on_broker_error(err, cls, *args, **kwargs)
return cls.app.AsyncResult(None, backend=cls.errbackend(),
task_name=cls.name)
def safetask(*args, **kwargs):
"""
Task factory returning safe tasks handling socket errors.
When a socket error occurs, the given callable *on_broker_error*
is called passing the exception object, the class of the task
and the original args and kwargs.
"""
if 'base' not in kwargs:
on_broker_error = kwargs.pop('on_broker_error', SafeTask.on_broker_error)
errbackend = kwargs.pop('errbackend', SafeTask.errbackend)
kwargs['base'] = type('SafeTask', (SafeTask,), {
'on_broker_error': staticmethod(on_broker_error),
'errbackend': errbackend,
'abstract': True,
})
return task(*args, **kwargs)
You can both subclass SafeTask or use the decorator #safetask.
If you can think of an improvement, don't hesitate to contribute.

Python: Anything wrong with dynamically assigning instance methods as instance attributes

I came up with the following code to decorate instance methods using a decorator that requires the instance itself as an argument:
from functools import wraps
def logging_decorator(tricky_instance):
def wrapper(fn):
#wraps(fn)
def wrapped(*a, **kw):
if tricky_instance.log:
print("Calling %s.." % fn.__name__)
return fn(*a, **kw)
return wrapped
return wrapper
class Tricky(object):
def __init__(self, log):
self.log = log
self.say_hi = logging_decorator(self)(self.say_hi)
def say_hi(self):
print("Hello, world!")
i1 = Tricky(log=True)
i2 = Tricky(log=False)
i1.say_hi()
i2.say_hi()
This seems to work great, but I fear that I may have overlooked some unintended side effects of this trick. Am I about to shoot myself in the foot, or is this safe?
Note that I don't actually want to use this for logging, it's just the shortest meaningful example I could come up with.
It's not really clear to me why you would ever want to do this. If you want to assign a new method type dynamically use types:
import types
class Tricky(object):
def __init__(self):
def method(self):
print('Hello')
self.method = types.MethodType(method, self)
If you want to do something with the instance, do it in the __init__ method. If you just want access to the method's instance inside the decorator, you can use the im_self attribute:
def decorator(tricky_instance):
def wrapper(meth):
print(meth.im_self == tricky_instance)
return meth
return wrapper
Personally, I think this is veering into Maybe-I-Shouldn't-Use-Decorators land.
I think I was trying to be needlessly smart. There seems to be an embarrassingly simpler solution:
from functools import wraps
def logging_decorator(fn):
#wraps(fn)
def wrapped(self, *a, **kw):
if self.log:
print("Calling %s.." % fn.__name__)
return fn(self, *a, **kw)
return wrapped
class Tricky(object):
def __init__(self, log):
self.log = log
#logging_decorator
def say_hi(self):
print("Hello, world!")
i1 = Tricky(log=True)
i2 = Tricky(log=False)
i1.say_hi()
i2.say_hi()