2013-04-28 56 views
2

我想用Qt4庫實現這種效果:一個按鈕組,它附着在它旁邊的每個按鈕。在Gtk3中,我只需將「鏈接」類應用於容器小部件。這怎麼能在Qt4中完成?讓Qt按鈕相互連接

enter image description here

回答

2

在Qt,創建一組鏈接按鈕,您可以使用QButtonGroup,內帶可檢查的按鈕。

請注意,這個類不是一個可視容器,你需要使用普通的佈局技術來佈置你的按鈕(或其他任何東西)。 (另一種方法是在QGroupBox,這確實有視覺外觀。)

這是相對簡單的使用一組框和style sheets來達到這種效果。從QPushButton styling examples,輕微的調整採取

#include <QtGui> 

// For Qt 5: 
// #include <QtWidgets> 

static QString strip_normal(
"QPushButton {" 
"   margin: 0; padding: 10px; border: 0px;" 
"   background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," 
"                              stop: 0 #f6f7fa, stop: 1 #aaabae);" 
"}"); 
static QString strip_checked(
"QPushButton:checked {" 
"   background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," 
"                              stop: 0 #aaabae, stop: 1 #f6f7fa);" 
"}"); 
static QString strip_first(
"QPushButton{" 
"   border-top-left-radius: 6px;" 
"   border-bottom-left-radius: 6px;" 
"}"); 
static QString strip_last(
"QPushButton{" 
"   border-top-right-radius: 6px;" 
"   border-bottom-right-radius: 6px;" 
"}"); 

static QString widget_back(
"QWidget {" 
"   background: black;" 
"}"); 

梯度。

class W: public QWidget 
{ 
    Q_OBJECT 
    public: 
        W(QWidget *parent = 0) 
            : QWidget(parent) 
        { 
            /* style sheet applies to this widget and its children */ 
      setStyleSheet(widget_back+strip_normal+strip_checked); 

      /* First and last widget need special borders */ 
            QPushButton *one = createButton("one",   true,  strip_first); 
            QPushButton *two = createButton("two",   false); 
            QPushButton *thr = createButton("three", false, strip_last); 

      /* Button group for button selection handling */ 
            QButtonGroup *bg = new QButtonGroup; 
            bg->addButton(one); 
            bg->addButton(two); 
            bg->addButton(thr); 

      /* Layout with no spacing */ 
            QHBoxLayout *hl = new QHBoxLayout; 
            hl->addWidget(one); 
            hl->addWidget(two); 
            hl->addWidget(thr); 
            hl->setSpacing(0); 

            setLayout(hl); 
        } 

        QPushButton *createButton(QString const& name, 
                                  bool checked, 
                                  QString const& sheet = QString()) 
        { 
            QPushButton *pb = new QPushButton(name); 
            pb->setCheckable(true); 
            pb->setChecked(checked); 
            if (!sheet.isEmpty()) 
                pb->setStyleSheet(sheet); 
            return pb; 
        } 
}; 

這看起來像下面的屏幕截圖(視操作系統而定,你可能擁有的任何Qt的定製上):

  • 的Linux,沒有造型責任:

    enter image description here

  • 樣式表如上面的代碼:

    enter image description here

其他的替代方案,可以幫助你,取決於什麼語義「控制」有你:QTabBar這是一個選項卡式窗口頂部部件(標籤選擇器)。

+0

謝謝,但我想要的是,對行爲的依賴,風格:按鈕彼此物理連接:) – 2013-04-28 22:04:18

+0

如何實現這一目標? :) – 2013-04-29 07:16:35

+0

@Alessandro Facciorusso:添加了一些適用樣式表的示例。您需要自己完成這些工作才能獲得所需的確切外觀。 (請不要多次打人,我第一次接到通知。) – Mat 2013-04-29 08:42:10