2012-11-14 32 views
0

當選擇單選按鈕時,GTK的「切換」信號觸發,但在此之前,它也會在取消選擇先前選定的單選按鈕時觸發。僅在選擇GTK無線電按鈕信號時才選擇

我正在使用一個使用單選按鈕的GUI,每個按鈕代表一組實體。這對「切換」信號中的第一個觸發了對GUI中其他字段的一些不需要的更新 - 我只希望在新選擇的按鈕觸發回調時發生更新。我該如何解決這個信號問題,並將回調函數限制爲僅對選擇進行操作而不是取消選擇?我在我編寫的類中考慮過一個標誌變量,但也許有更多GTK認可的技術。

回答

0

我不認爲你可以只有得到選擇信號,但你可以做別的事情。您可以編寫信號處理程序,以便獲取已切換的按鈕(假設您正在爲多個按鈕重複使用相同的處理程序)。然後你可以檢查它的狀態,看它是否被選中或取消選擇。

你做到這一點的方法是用適配器連接:

// do this for each button (this one is for "buttona"): 
buttona.signal_toggled().connect(
    sigc::bind(
     sigc::mem_fun(*this, &myclass::handle_button_toggled), 
     buttona 
    ) 
); 

在你的類,handle_button_toggled包括按鈕參數:

myclass { 
    Gtk::ToggleButton buttona, buttonb, ... 
    .... 
    void handle_button_toggled(Gtk::ToggleButton &b) { 
    ...check state of b ... 
    } 
} 

在C++ 11,您也可以使用lambda表達式:

buttona.signal_toggled().connect([this,&buttona]{ 
    handled_button_toggled(buttona); 
}); 
+0

我錯誤地認爲這也可以通過連接'激活'信號而不是'切換'信號來實現嗎? – bluppfisk

0
// C++11 
#include <gtkmm.h> 
#include <iostream> 
#include <vector> 

using namespace std; 

class RadioBox 
{ 
public: 
    Gtk::Box      {Gtk::ORIENTATION_HORIZONTAL}; 
    vector<Gtk::RadioButton*> rb_list; 
    string      selected_text; 
    int       selected_pos; 

    RadioBox(int defpos, 
      std::initializer_list<string> rb_name) 
    { 
     add(box); 
     int i = 0; 
     for (auto& rb_name_i : rb_name) { 
      Gtk::RadioButton* rb = new Gtk::RadioButton{rb_name_i}; 
      rb_list.push_back(rb); 
      if (i==defpos) { 
      rb->set_active(); 
      } 
      box.pack_start(*rb, 0, 0); 
      if (i != 0) { 
      rb->join_group(*rb_list[0]); 
      } 
      rb->signal_toggled().connect(
      sigc::bind(
       sigc::mem_fun(*this, &LabRadio::clicked), 
       rb, 
       i 
      )); 
      i++; 
     } 
    } 

    void clicked(Gtk::RadioButton* rb, int pos) { 
     if (!rb) return; 
     if (rb->get_active()) { 
     selected_pos = pos; 
     selected_text = rb->get_label().c_str(); 
     cout << "RadioButton:selected" 
       << " pos:" << selected_pos 
       << " text:" << selected_text 
       << "\n"; 
     } 
    } 

    ~RadioBox() { 
     rb_count = rb_list.size(); 
     for(int i=0; i < rb_count; ++i) { 
      if (rb_list[i]) delete rb_list[i]; 
     } 
    } 

}; 


//USAGE: 

class mywindow : public Gtk::Window { 
    public: 
    RadioBox myradiobox {2, {"Apples", "Pears", "Oranges", "Peaches"}}; 

    // ... your code here 

    mywindow() { 
    // ... 
    <somewidget>.pack_start(myradiobox.box); 
    // ... 
    } 

};