2015-12-23 2 views
0

Я создаю пользовательский GridCellEditor для того, чтобы использовать алгоритм levenshtein и предлагать строки в зависимости от введенного значения пользователя.Фокус Combobox пользовательского GridCellEditor on Begin Редактировать

class GridCellLevenshteinEditor(wx.grid.PyGridCellEditor): 

    """A Grid Cell Editor with a combobox that offers choices sorted 
    with the levenshtein algorithm.""" 

    def __init__(self, choices, allow_new_entries=False): 
     wx.grid.PyGridCellEditor.__init__(self) 
     # this holds all the possible strings, that can be selected 
     self.choices = choices 
     self.allow_new_entries = allow_new_entries 

     self.start_value = None 
     self.combobox = None 

    def Create(self, parent, id, evt_handler): 
     """Creates the actual edit control.""" 
     self.combobox = ComboBox(parent, None, self.choices, doSort=False, 
           style=wx.CB_SIMPLE) 
     self.SetControl(self.combobox) 
     if evt_handler: 
      self.combobox.PushEventHandler(evt_handler) 

    def BeginEdit(self, row, col, grid): 
     """Fetch the value from the table and prepare the edit control 
     to begin editing. 
     This function should save the original value of the grid cell at the 
     given row and col and show the control allowing the user to 
     change it.""" 
     self.start_value = grid.GetTable().GetValue(row, col) 
     if self.start_value in ("", None): 
      self.start_value = "test" 
     self.combobox.ChangeValue(self.start_value) 
     self.combobox.SetFocus() # <-- this causes an issue 

    def set_new_choices(self, new_choices): 
     """Empties the Combobox Control and fills it with the new given 
     choices. Can be used as well for example for updating the choices.""" 
     self.choices = new_choices 
     self.combobox.refresh_combo_box(new_choices, False) 

Без self.combobox.SetFocus() это выглядит, как это в сетке:

LevenshteinEditor without Focus

Теперь я хочу, чтобы текстовое поле ComboBox, где пользователь может ввести, автоматически фокусируется, когда начинается редактирование. Поэтому я добавил self.combobox.SetFocus(), но это вызывает только проблемы. Выпадающий список ComboBox будет показан в течение нескольких миллисекунд, а затем снова закроется, а затем процесс редактирования завершится автоматически. Значит, мне нужно будет снова щелкнуть по ячейке, чтобы снова начать процесс редактирования, хотя это будет немедленно завершено само по себе из-за SetFocus().

Кто-нибудь знает, как разрешить вводимый пользователем текст автоматически выбираться при запуске процесса редактирования ячейки сетки, без комбобокса, действующего странным образом?

ответ

0

Я нашел решение моей проблемы здесь: http://wxpython-users.1045709.n5.nabble.com/Combo-box-as-grid-cell-editor-td2360176.html

Когда я изменил фокус обработчик событий по умолчанию думал, что я закончил редактирование и названный EndEdit(). Из-за этого мне пришлось переопределить обработку событий для моего редактора combobox, добавив PushEventHandler(wx.EvtHandler()).

Поэтому мне пришлось изменить следующие методы.

def Create(self, parent, dummy_id, dummy_evt_handler): 
"""Creates the actual edit control.""" 
    self.combobox = ComboBox(parent, None, self.choices, doSort=False, 
          style=wx.CB_DROPDOWN | wx.TE_PROCESS_ENTER) 
    self.SetControl(self.combobox) 
    self.combobox.PushEventHandler(wx.EvtHandler()) 
    self.combobox.Bind(wx.EVT_TEXT_ENTER, self.process_enter, 
         self.combobox) 

def process_enter(self, dummy_event): 
    """This gets called, when the enter key was pressed in the combobox.""" 
    # end edit and select next cell 
    self.grid.DisableCellEditControl() 
    self.grid.MoveCursorRight(False) 

def BeginEdit(self, row, col, grid): 
    """Fetch the value from the table and prepare the edit control 
    to begin editing. 
    This function should save the original value of the grid cell at the 
    given row and col and show the control allowing the user to 
    change it.""" 
    self.grid = grid 
    self.start_value = grid.GetTable().GetValue(row, col) 
    self.combobox.ChangeValue(self.start_value) 
    self.combobox.SetFocus() 
Смежные вопросы