Browse Source

LibGUI: Allow basic keyboard navigation in GTableView.

Pressing Enter will now "activate" the selected index, meaning that
the model gets a call to activate(GModelIndex).
Andreas Kling 6 năm trước cách đây
mục cha
commit
b5dcad932e
3 tập tin đã thay đổi với 32 bổ sung1 xóa
  1. 6 1
      LibGUI/GTableModel.h
  2. 23 0
      LibGUI/GTableView.cpp
  3. 3 0
      LibGUI/GTableView.h

+ 6 - 1
LibGUI/GTableModel.h

@@ -47,13 +47,18 @@ public:
     virtual ColumnMetadata column_metadata(int) const { return { }; }
     virtual GVariant data(int row, int column) const = 0;
     virtual void update() = 0;
+    virtual void activate(const GModelIndex&) { }
 
     bool is_valid(GModelIndex index) const
     {
         return index.row() >= 0 && index.row() < row_count() && index.column() >= 0 && index.column() < column_count();
     }
 
-    void set_selected_index(const GModelIndex& index) { m_selected_index = index; }
+    void set_selected_index(const GModelIndex& index)
+    {
+        if (is_valid(index))
+            m_selected_index = index;
+    }
     GModelIndex selected_index() const { return m_selected_index; }
 
     void register_view(Badge<GTableView>, GTableView&);

+ 23 - 0
LibGUI/GTableView.cpp

@@ -2,6 +2,7 @@
 #include <LibGUI/GTableModel.h>
 #include <LibGUI/GScrollBar.h>
 #include <SharedGraphics/Painter.h>
+#include <Kernel/KeyCode.h>
 
 GTableView::GTableView(GWidget* parent)
     : GWidget(parent)
@@ -167,3 +168,25 @@ int GTableView::item_count() const
 {
     return m_model->row_count();
 }
+
+void GTableView::keydown_event(GKeyEvent& event)
+{
+    if (!model())
+        return;
+    auto& model = *this->model();
+    if (event.key() == KeyCode::Key_Return) {
+        model.activate(model.selected_index());
+        return;
+    }
+    if (event.key() == KeyCode::Key_Up) {
+        model.set_selected_index({ model.selected_index().row() - 1, model.selected_index().column() });
+        update();
+        return;
+    }
+    if (event.key() == KeyCode::Key_Down) {
+        model.set_selected_index({ model.selected_index().row() + 1, model.selected_index().column() });
+        update();
+        return;
+    }
+    return GTableView::keydown_event(event);
+}

+ 3 - 0
LibGUI/GTableView.h

@@ -24,12 +24,15 @@ public:
     int content_width() const;
     int horizontal_padding() const { return m_horizontal_padding; }
 
+    virtual bool accepts_focus() const override { return true; }
+
 private:
     virtual void model_notification(const GModelNotification&);
 
     virtual void paint_event(GPaintEvent&) override;
     virtual void resize_event(GResizeEvent&) override;
     virtual void mousedown_event(GMouseEvent&) override;
+    virtual void keydown_event(GKeyEvent&) override;
 
     void update_scrollbar_ranges();
     int item_count() const;