1.文本自动折行显示
// 只处理字符串,在合适的位置插入\n或者 <br/>
QString Widget::dealText(const QString& org)
{
QString result;
QFontMetrics fm(fontMetrics());
int textWidthInPxs = fm.horizontalAdvance(org); // 获取文本宽度(若Qt5.7则使用width)
const int rear = org.length();
int pre = 0, vernier = 1;
int pickUpWidthPxs = 0;
QString pickUp;
unsigned int curLen = 0;
if (textWidthInPxs <= ui->label->width()) {
result = org;
return result;
}
while (vernier <= rear) {
curLen = vernier - pre;
pickUp = org.mid(pre, curLen);
pickUpWidthPxs = fm.horizontalAdvance(pickUp);
if (pickUpWidthPxs >= ui->label->width()) {
result += pickUp + "\n"; // 插入换行符,或者使用<br/>标签
pre = vernier;
pickUpWidthPxs = 0;
}
++vernier;
}
if (pickUpWidthPxs < ui->label->width() && !pickUp.isEmpty()) {
result += pickUp;
}
return result;
}
2.使用
常规的使用
QWidget::setToolTip();
// 例如
ui->label->setToolTip("abc");
高级用法
// 使用类型的 QEvent::ToolTip的QHelpEvent事件(注意ignore使用)
bool SortingBox::event(QEvent *event)
{
if (event->type() == QEvent::ToolTip) {
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(event);
if (xxxxxx) {
QToolTip::showText(helpEvent->globalPos(), "xxxxxxxxx");
} else {
QToolTip::hideText();
event->ignore();
}
return true;
}
return QWidget::event(event);
}
立即显示 tooltip,就像上面用的,直接调用 showText()