wxPython: Вызов события вручную

, struct, и, в частности, readonly struct, я планирую уделить больше внимания в версии 3, в которой есть планы для новых API-интерфейсов сериализатора. Между тем, это не тот сценарий, с которым он хорошо справляется, но ваша лучшая ставка может быть «суррогатами» - это означает, что сериализатор в значительной степени игнорирует Amount, используя что-то еще вместо этого для более удобной сериализации. Это также означает, что вы можете удалить любые атрибуты сериализатора или API из Amount:

using ProtoBuf;
using ProtoBuf.Meta;

static class P
{
    static void Main()
    {
        // only need to do this once, *before*
        // serializing/deserialing anything
        RuntimeTypeModel.Default.Add(typeof(Amount), false)
            .SetSurrogate(typeof(AmountSurrogate));

        // test it works
        var obj = new Foo { Amount = new Amount(123.45M) };
        var clone = Serializer.DeepClone(obj);
        System.Console.WriteLine(clone.Amount.Value);
    }
}
[ProtoContract]
public class Foo
{
    [ProtoMember(1)]
    public Amount Amount { get; set; }
}

[ProtoContract]
struct AmountSurrogate
{ // a nice simple type for serialization
    [ProtoMember(1)]
    public long Value { get; set; }

    // operators define how to get between the two types
    public static implicit operator Amount(AmountSurrogate value)
        => Amount.CreateFrom(value.Value);
    public static implicit operator AmountSurrogate(Amount value)
        => new AmountSurrogate { Value = value.ScaledValue };
}
20
задан Ram Rachum 14 April 2009 в 14:14
поделиться

3 ответа

Я думаю, что вы хотите wx.PostEvent .

Также есть некоторая информация о публикации событий из другого потока для долго выполняющихся задач в wxPython wiki .

10
ответ дан 29 November 2019 в 22:38
поделиться

You mean you want to have an event dispatch?

::wxPostEvent void wxPostEvent(wxEvtHandler *dest, wxEvent& event)

In a GUI application, this function posts event to the specified dest object using wxEvtHandler::AddPendingEvent. Otherwise, it dispatches event immediately using wxEvtHandler::ProcessEvent. See the respective documentation for details (and caveats).

Include files

wxPython API docs

0
ответ дан 29 November 2019 в 22:38
поделиться

Old topic, but I think I've got this figured out after being confused about it for a long time, so if anyone else comes through here looking for the answer, this might help.

To manually post an event, you can use

self.GetEventHandler().ProcessEvent(event)

(wxWidgets docs here, wxPython docs here)

or

wx.PostEvent(self.GetEventHandler(), event)

(wxWidgets docs, wxPython docs)

where event is the event you want to post. Construct the event with e.g.

wx.PyCommandEvent(wx.EVT_BUTTON.typeId, self.GetId())

if you want to post a EVT_BUTTON event. Making it a PyCommandEvent means that it will propagate upwards; other event types don't propagate by default.

You can also create custom events that can carry whatever data you want them to. Here's an example:

myEVT_CUSTOM = wx.NewEventType()
EVT_CUSTOM = wx.PyEventBinder(myEVT_CUSTOM, 1)

class MyEvent(wx.PyCommandEvent):
    def __init__(self, evtType, id):
        wx.PyCommandEvent.__init__(self, evtType, id)
        myVal = None

    def SetMyVal(self, val):
        self.myVal = val

    def GetMyVal(self):
        return self.myVal

(I think I found this code in a mailing list archive somewhere, but I can't seem to find it again. If this is your example, thanks! Please add a comment and take credit for it!)

So now, to Post a custom event:

event = MyEvent(myEVT_CUSTOM, self.GetId())
event.SetMyVal('here is some custom data')
self.GetEventHandler().ProcessEvent(event)

and you can bind it just like any other event

self.Bind(EVT_CUSTOM, self.on_event)

and get the custom data in the event handler

def on_event(self, e):
    data = e.GetMyVal()
    print 'custom data is: {0}'.format(data)

Or include the custom data in the event constructor and save a step:

class MyEvent(wx.PyCommandEvent):
    def __init__(self, evtType, id, val = None):
        wx.PyCommandEvent.__init__(self, evtType, id)
        self.myVal = val

etc.

Hope this is helpful to someone.

56
ответ дан 29 November 2019 в 22:38
поделиться
Другие вопросы по тегам:

Похожие вопросы: