Qt實現新手引導
對于一個新安裝的軟件或者一個新的功能,提供一個新手引導步驟,能夠讓用戶快速熟悉。
這是最終效果,每一個按鈕都會有一個簡單引導,通過點擊上一步、下一步來切換不同的指導。當前引導的功能,會有一個高光區,該高光區可點擊,其他區域不可點擊。引導結束后回歸主界面。
引導層
void GuideOverlayTip::updateWidgets()
{if (m_currentStep >= m_highlightRects.size()){hide();return;}if(m_currentStep == m_highlightRects.size() - 1){m_btnPrev->setText(tr("完成"));}QRect rect = m_highlightRects[m_currentStep];m_tipLabel->setText(m_tips[m_currentStep]);m_tipLabel->adjustSize();m_tipLabel->move(rect.topRight() + QPoint(10, -rect.height()/2));if(m_currentStep != 0){m_btnPrev->move(rect.bottomLeft() + QPoint(-80, 10));m_btnPrev->show();}else{m_btnPrev->hide();}m_btnNext->move(rect.bottomRight() + QPoint(10, 10));
}
根據當前引導,更新btn、label順序、文本顯示。
void GuideOverlayTip::updateMask()
{if (m_currentStep >= m_highlightRects.size()){return;}QRegion fullRegion(rect());QRegion highlightRegion(m_highlightRects[m_currentStep].adjusted(0, 0, 1, 1), QRegion::Rectangle);QRegion maskedRegion = fullRegion.subtracted(highlightRegion);setMask(maskedRegion);
}
setMask可以遮擋非高光區的事件。
void GuideOverlayTip::paintEvent(QPaintEvent *)
{QPainter painter(this);QPainterPath maskPath;maskPath.addRect(rect());maskPath.addRoundedRect(m_highlightRect, 8, 8);maskPath.setFillRule(Qt::OddEvenFill);painter.fillPath(maskPath, QColor(0, 0, 0, 160));
}
根據需求繪制一個半透明的背景。
調用層
void MainWindow::showGuide()
{QList<QRect> steps;QStringList tips;for (int i = btn1; i <= btn4; ++i){QPushButton* btn = m_pushBtns[i];QRect btnRect(this->mapFromGlobal(btn->mapToGlobal(QPoint(0, 0))), btn->size());steps << btnRect;}qDebug() << steps;tips << "點擊這里改變改變背景顏色為A";tips << "點擊這里改變改變背景顏色為B";tips << "點擊這里改變改變背景顏色為C";tips << "點擊這里恢復默認背景";m_guide->setSteps(steps, tips);m_guide->start();}
傳入高光區位置、提示文本等;
其中為m_guide = new GuideOverlayTip(this);