原 UI 將 5 個 RadioButton 分兩組:前三個 (radioBtn1-3) 與後兩個 (radioBtn4-5) 各置於一個 VerticalLayout。程式碼設定選中狀態,兩組獨立運作互不干擾。
修改 UI 後,將兩組置於同一 VerticalLayout,程式碼未變,執行發現前三個永無法選中,僅後兩個正常。
Qt Assistant 文件說明:
Radio buttons are autoExclusive by default. If auto-exclusive is enabled, radio buttons that belong to the same parent widget behave as if they were part of the same exclusive button group. If you need multiple exclusive button groups for radio buttons that belong to the same parent widget, put them into a QButtonGroup.
同屬一個父 Widget 的 RadioButton 預設為 autoExclusive。程式碼中 radioBtn2 雖被選中,但後續 radioBtn4 將其衝掉。
使用 QButtonGroup (父為 QObject) 或 QGroupBox (父為 QWidget) 將兩組分開:
// in ctor ui.setupUi(this); QButtonGroup *btnGroup = new QButtonGroup(this); btnGroup->addButton(ui.radAllConnections); btnGroup->addButton(ui.radListedConnections); btnGroup->addButton(ui.radNoTrust);
檢視原始 UI 產生代碼發現:雖然設計器顯示兩個 VerticalLayout,但實際各自包裹在一個 QWidget (layoutWidget2, layoutWidget3) 中,RadioButton 的 parent 為這兩個 Widget,故不屬於同一父 Widget,可各自 autoExclusive。
修改後,兩組 RadioButton 直接置於同一 VerticalLayout,連同其他 Widget 放在同一 Page (QWidget) 上。產生代碼顯示:5 個 RadioButton 的 parent 全變為同一個 settings_firewall_page!
TrollTech 可能為優化 UI 檔案結構而移除中間 Widget。安全起見:
QGroupBox。QButtonGroup 明確分組。