QMenuBar的自繪處理和彈出位置控制


www.qt-ui.com 原創技術文章

QMenu中沒有提供菜單彈出方向的參數,所以需要我們自行計算菜單位置。

先通過addAction把需要的菜單項目全部添加好,然后調用sizeHine獲取菜單大小。

然后在exec里面計算出最后顯示的位置即可。

QMenu的自繪可以通過重載paintEvent來實現,通過actionGeometry來得到每一項的位置, 然后根據類型進行繪制。

 const QList<QAction*>& actions = pMenu->actions(); for (int i = 0; i < actions.size(); ++i) { QAction* pAction = actions.at(i); QRect rect = pMenu->actionGeometry(pAction); if (i == _hotItemIdx && !pAction->isSeparator()) { drawFillStyle(*pPainter, _itemStyle[UIG_HOT], rect); drawText(*pPainter, pAction->text(), _textStyle[UIG_HOT], rect); } else { drawFillStyle(*pPainter, _itemStyle[UIG_NORMAL], rect); drawText(*pPainter, pAction->text(), _textStyle[UIG_NORMAL], rect); } if (pAction->isSeparator()) { // draw seperator } else if (pAction->isCheckable()) { // draw check style } else { // to do other type paint } if (pAction->menu()) { QBrush brush; brush.setStyle(Qt::SolidPattern); brush.setColor(0xffcccccc); QPainterPath path; path.moveTo(QPointF(rect.right() - 2, rect.top() + rect.height() / 2)); path.lineTo(QPointF(rect.right() - 2 - 5, rect.top() + rect.height() / 2 - 5)); path.lineTo(QPointF(rect.right() - 2 - 5, rect.top() + rect.height() / 2 + 5)); path.closeSubpath(); pPainter->fillPath(path, brush); } } 

菜單文字中遇到&需要額外進行分割合理,將帶有&的文字換成下划線字體文字進行繪制。 通過qt的QFontMetrics來計算文字長度。

QFont font;
        font.setPixelSize(textStyle._font.fontSize);
        font.setFamily(textStyle._font.fontFamily);
        font.setBold(textStyle._font.bold);
        font.setItalic(textStyle._font.italic);
        font.setUnderline(textStyle._font.underline);

        QString text = item.data(USER_CONTENT).toString();

        QStringList list = text.split("&"); int height = 0; QFontMetrics fm(font); if (list.size() > 1) { for (size_t i = 0; i < list.size(); i++) { int totalWidth = fm.width(list.at(i)); } ... }

 

 Qt-UI C++Python界面開發工具 UI開發工具 qt解決方案 qt開源項目

更多詳情請瀏覽

www.qt-ui.com

www.qt-ui.com.cn

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM