2017-01-22 81 views
0

我有一個QMenuBar,例如兩個QMenu項目。Qt stylesheet:設置一個特定的QMenuBar :: item背景顏色

enter image description here

我怎麼能只讓「地板」項目是藍色的,例如?我知道如何改變它所有的項目與:

QMenuBar::item { 
    background: ...; 
} 

但我找不到一種方法來爲特定項目着色。我試圖使用setPropertyQmenu,我嘗試了setPalette,...我只是發現沒有任何工作。有沒有辦法在C++代碼中設置特定的QMenuBar::item屬性?

回答

0

我終於找到了一些東西。

  1. 創建自己的對象,例如WidgetMenuBar,從QMenuBar繼承。

  2. 添加屬性標識至極項目應着不同的顏色:小工具的

    for (int i = 0; i < this->actions().size(); i++){ 
        actions().at(i)->setProperty("selection",false); 
    } 
    // Only the first item colored 
    actions().at(0)->setProperty("selection",true); 
    
  3. 重新實現void paintEvent(QPaintEvent *e)功能:

    void WidgetMenuBarMapEditor::paintEvent(QPaintEvent *e){ 
        QPainter p(this); 
        QRegion emptyArea(rect()); 
    
        // Draw the items 
        for (int i = 0; i < actions().size(); ++i) { 
         QAction *action = actions().at(i); 
         QRect adjustedActionRect = this->actionGeometry(action); 
    
         // Fill by the magic color the selected item 
         if (action->property("selection") == true) 
          p.fillRect(adjustedActionRect, QColor(255,0,0)); 
    
         // Draw all the other stuff (text, special background..) 
         if (adjustedActionRect.isEmpty() || !action->isVisible()) 
          continue; 
         if(!e->rect().intersects(adjustedActionRect)) 
          continue; 
         emptyArea -= adjustedActionRect; 
         QStyleOptionMenuItem opt; 
         initStyleOption(&opt, action); 
         opt.rect = adjustedActionRect; 
         style()->drawControl(QStyle::CE_MenuBarItem, &opt, &p, this); 
        } 
    } 
    

你可以看到here如何實現的paintEvent功能。