Grid cell with date time editor and renderer

Hi,

I need a custom wx.grid cell editor and renderer which will accept only datetime values and represent them in date time format. Is there such a cus to editor and renderer?

Best Regards

There’s a renderer class that uses wx.DateTime values, I’m not sure why there isn’t an editor class for it. See GridCellDateTimeRenderer in the docs. If you want to deal with Python datetime objects instead then you need to create your own.

···

On Wednesday, July 3, 2019 at 8:32:18 AM UTC-7, steve wrote:

Hi,
I need a custom wx.grid cell editor and renderer which will accept only datetime values and represent them in date time format. Is there such a cus to editor and renderer?

Robin

https://docs.wxpython.org/wx.grid.GridCellDateTimeRenderer.html?highlight=gridcelldatetimerenderer should do the job!

···

-----Original Message-----
From: wxpython-users@googlegroups.com <wxpython-users@googlegroups.com> On Behalf Of steve
Sent: 03 July 2019 16:32
To: wxPython-users <wxpython-users@googlegroups.com>
Subject: [wxPython-users] Grid cell with date time editor and renderer

Hi,

I need a custom wx.grid cell editor and renderer which will accept only datetime values and represent them in date time format. Is there such a cus to editor and renderer?

Best Regards

--
You received this message because you are subscribed to the Google Groups "wxPython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to wxpython-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/wxpython-users/3f2c44cf-dd44-4fc5-95ae-9dde37e3ffd6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Hi,

I wrote the following custom editor, it should pop up a wx.adv.DatePickerCtrl object when double clicking the gird cell, but I get “AttributeError: ‘MyCellEditor’ object has no attribute ‘_tc’” error. Coudld you please help?

renderer = MyCellEditor()
attr = wx.grid.GridCellAttr()
attr.SetEditor(renderer)
self.My_grid.SetColAttr(1, attr)
#!/usr/bin/env python

import string

import wx
import wx.grid as gridlib
from datetime import datetime, timedelta
from utilities.functions import *
import sys

<details class='elided'>
<summary title='Show trimmed content'>&#183;&#183;&#183;</summary>

#---------------------------------------------------------------------------
class MyCellEditor(gridlib.GridCellEditor):
    """
    This is a sample GridCellEditor that shows you how to make your own custom
    grid editors. All the methods that can be overridden are shown here. The
    ones that must be overridden are marked with "*Must Override*" in the
    docstring.
    """
    def __init__(self):
        self.log = sys.stdout
        self.log.write("MyCellEditor ctor\n")
        gridlib.GridCellEditor.__init__(self)

    def Create(self, parent, id, evtHandler):
        """
        Called to create the control, which must derive from wx.Control.
        *Must Override*
        """
        print("created ctrl")
        self.log.write("MyCellEditor: Create\n")
        self._tc = wx.adv.DatePickerCtrl(self, size=(120,-1),style=wx.adv.DP_DROPDOWN|wx.adv.DP_SHOWCENTURY)
        today = datetime.now()
        today = datetime(today.year, today.month, today.day)
        self._tc.SetValue(datetime_to_wxdate(today))
        self.SetControl(self._tc)

        if evtHandler:
            self._tc.PushEventHandler(evtHandler)

    def SetSize(self, rect):
        """
        Called to position/size the edit control within the cell rectangle.
        If you don't fill the cell (the rect) then be sure to override
        PaintBackground and do something meaningful there.
        """
        self.log.write("MyCellEditor: SetSize %s\n" % rect)
        self._tc.SetSize(rect.x, rect.y, rect.width+2, rect.height+2,
                               wx.SIZE_ALLOW_MINUS_ONE)

    def Show(self, show, attr):
        """
        Show or hide the edit control. You can use the attr (if not None)
        to set colours or fonts for the control.
        """
        self.log.write("MyCellEditor: Show(self, %s, %s)\n" % (show, attr))
        super(MyCellEditor, self).Show(show, attr)

    def PaintBackground(self, rect, attr):
        """
        Draws the part of the cell not occupied by the edit control. The
        base class version just fills it with background colour from the
        attribute. In this class the edit control fills the whole cell so
        don't do anything at all in order to reduce flicker.
        """
        self.log.write("MyCellEditor: PaintBackground\n")

    def BeginEdit(self, row, col, grid):
        """
        Fetch the value from the table and prepare the edit control
        to begin editing. Set the focus to the edit control.
        *Must Override*
        """
        self.log.write("MyCellEditor: BeginEdit (%d,%d)\n" % (row, col))
        self.startValue = grid.GetTable().GetValue(row, col)
        try:
            tmpDate = wx.DateTime()
            tmpDate.ParseFormat(self.startValue, "%d-%b-%y")
            self._tc.SetValue(tmpDate)
            self._tc.SetFocus()
        except:
            today = datetime.now()
            today = datetime(today.year, today.month, today.day)
            self._tc.SetValue(datetime_to_wxdate(today))
            self._tc.SetFocus()

        # For this example, select the text
        # self._tc.SetSelection(0, self._tc.GetLastPosition())

    def EndEdit(self, row, col, grid, oldVal):
        """
        End editing the cell. This function must check if the current
        value of the editing control is valid and different from the
        original value (available as oldval in its string form.) If
        it has not changed then simply return None, otherwise return
        the value in its string form.
        *Must Override*
        """
        self.log.write("MyCellEditor: EndEdit (%s)\n" % oldVal)
        val = self._tc.GetValue()
        val_datetime = wxdate_to_datetime3(val)
        val_str = val_datetime.strftime("%d-%b-%y")
        if val != oldVal: #self.startValue:
            return val
        else:
            return None

    def ApplyEdit(self, row, col, grid):
        """
        This function should save the value of the control into the
        grid or grid table. It is called only after EndEdit() returns
        a non-None value.
        *Must Override*
        """
        self.log.write("MyCellEditor: ApplyEdit (%d,%d)\n" % (row, col))
        val = self._tc.GetValue()
        val_datetime = wxdate_to_datetime3(val)
        val_str = val_datetime.strftime("%d-%b-%y")
        grid.GetTable().SetValue(row, col, val_str) # update the table

        self.startValue = ''
        today = datetime.now()
        today = datetime(today.year, today.month, today.day)
        self._tc.SetValue(datetime_to_wxdate(today))

    def Reset(self):
        """
        Reset the value in the control back to its starting value.
        *Must Override*
        """
        self.log.write("MyCellEditor: Reset\n")
        if self.startValue == "":
            today = datetime.now()
            today = datetime(today.year, today.month, today.day)
            self._tc.SetValue(datetime_to_wxdate(today))
        else:
            try:
                tmpDate = wx.DateTime()
                tmpDate.ParseFormat(self.startValue, "%d-%b-%y")
                self._tc.SetValue(tmpDate)
            except:
                today = datetime.now()
                today = datetime(today.year, today.month, today.day)
                self._tc.SetValue(datetime_to_wxdate(today))

    def IsAcceptedKey(self, evt):
        """
        Return True to allow the given key to start editing: the base class
        version only checks that the event has no modifiers. F2 is special
        and will always start the editor.
        """
        self.log.write("MyCellEditor: IsAcceptedKey: %d\n" % (evt.GetKeyCode()))

        ## We can ask the base class to do it
        #return super(MyCellEditor, self).IsAcceptedKey(evt)

        # or do it ourselves
        return (not (evt.ControlDown() or evt.AltDown()) and
                evt.GetKeyCode() != wx.WXK_SHIFT)

    def StartingKey(self, evt):
        """
        If the editor is enabled by pressing keys on the grid, this will be
        called to let the editor do something about that first key if desired.
        """
        self.log.write("MyCellEditor: StartingKey %d\n" % evt.GetKeyCode())
        # key = evt.GetKeyCode()
        # ch = None
        # if key in [ wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3,
        # wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7,
        # wx.WXK_NUMPAD8, wx.WXK_NUMPAD9
        # ]:
        #
        # ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
        #
        # elif key < 256 and key >= 0 and chr(key) in string.printable:
        # ch = chr(key)
        #
        # if ch is not None:
        # # For this example, replace the text. Normally we would append it.
        # #self._tc.AppendText(ch)
        # self._tc.SetValue(ch)
        # self._tc.SetInsertionPointEnd()
        # else:
        # evt.Skip()
        evt.Skip()

    def StartingClick(self):
        """
        If the editor is enabled by clicking on the cell, this method will be
        called to allow the editor to simulate the click on the control if
        needed.
        """
        self.log.write("MyCellEditor: StartingClick\n")

    def Destroy(self):
        """final cleanup"""
        self.log.write("MyCellEditor: Destroy\n")
        super(MyCellEditor, self).Destroy()

    def Clone(self):
        """
        Create a new object which is the copy of this one
        *Must Override*
        """
        self.log.write("MyCellEditor: Clone\n")
        return MyCellEditor()

On Thursday, July 4, 2019 at 8:05:14 AM UTC+3, Gadget Steve wrote:

https://docs.wxpython.org/wx.grid.GridCellDateTimeRenderer.html?highlight=gridcelldatetimerenderer should do the job!

-----Original Message-----

From: wxpytho...@googlegroups.com wxpytho...@googlegroups.com On Behalf Of steve

Sent: 03 July 2019 16:32

To: wxPython-users wxpytho...@googlegroups.com

Subject: [wxPython-users] Grid cell with date time editor and renderer

Hi,

I need a custom wx.grid cell editor and renderer which will accept only datetime values and represent them in date time format. Is there such a cus to editor and renderer?

Best Regards


You received this message because you are subscribed to the Google Groups “wxPython-users” group.

To unsubscribe from this group and stop receiving emails from it, send an email to wxpytho...@googlegroups.com.

To view this discussion on the web visit https://groups.google.com/d/msgid/wxpython-users/3f2c44cf-dd44-4fc5-95ae-9dde37e3ffd6%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.