mlabel.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include "mlabel.h"
  2. #include <QPainter>
  3. #include <QTimer>
  4. #include <QFontMetrics>
  5. #include <QTimerEvent>
  6. const QString strSpace(" ");
  7. MLabel::MLabel(QWidget *parent) : QLabel(parent),left(0),timerId(-1),fontSize(10)
  8. {
  9. setStyleSheet(QString("color:black;"));
  10. }
  11. void MLabel::setText(const QString & txt)
  12. {
  13. QLabel::setText(txt);
  14. upateLabelRollingState();
  15. }
  16. void MLabel::paintEvent(QPaintEvent *e)
  17. {
  18. QPainter p(this);
  19. QRect rc = rect();
  20. rc.setHeight(rc.height() - 2);
  21. rc.setWidth(rc.width() - 2);
  22. QFont ft = font();
  23. ft.setPointSize(fontSize);
  24. p.setFont(ft);
  25. p.setPen(QPen(Qt::black));
  26. // 设置绘制文字的开始位置,也就是将文字往左移动多少
  27. rc.setLeft(rc.left() - left);
  28. // 如果文字已经显示到末尾,则再添加一遍文字,做出循环滚动的效果
  29. QString strText = text();
  30. if (timerId >= 0) {
  31. strText += strSpace + text();
  32. }
  33. // 绘制文字
  34. p.drawText(rc, Qt::AlignVCenter, strText);
  35. }
  36. void MLabel::timerEvent(QTimerEvent *e)
  37. {
  38. if (e->timerId() == timerId && isVisible()) {
  39. // 每次左移1个像素
  40. left += 1;
  41. // 判断是否已经完成一遍循环,完成则恢复起始位置,重新开始循环
  42. QFont ft = font();
  43. ft.setPointSize(fontSize);
  44. QFontMetrics fm(ft);
  45. const int txtWidth = fm.width(text());
  46. const int spaceWidth = fm.width(strSpace);
  47. if ((txtWidth + spaceWidth) < left) {
  48. left = 0;
  49. }
  50. repaint();
  51. }
  52. QLabel::timerEvent(e);
  53. }
  54. void MLabel::resizeEvent(QResizeEvent *e)
  55. {
  56. QLabel::resizeEvent(e);
  57. upateLabelRollingState();
  58. }
  59. void MLabel::upateLabelRollingState()
  60. {
  61. // 获取文本大小,小于文本框长度,则无需滚动
  62. QFont ft = font();
  63. ft.setPointSize(fontSize);
  64. QFontMetrics fm(ft);
  65. int nW = fm.width(text());
  66. left = 0;
  67. // 开启文本框滚动
  68. if (nW > width()) {
  69. timerId = startTimer(100);
  70. }
  71. // 关闭文本框滚动
  72. else {
  73. if (timerId >= 0) {
  74. killTimer(timerId);
  75. timerId = -1;
  76. }
  77. }
  78. }