当先锋百科网

首页 1 2 3 4 5 6 7

在上一遍文章介绍加载字体库来实现LCD显示数字,本篇介绍使用源码来实现,动手自己写源码。在UI下QLCDNumber控件实现了LCD数字显示,观看该控件的源码,实现自己的LCD数字显示。

首先定义一个类,例如“LCDNumberItem”继承QQuickPaintedItem类。h文件如下所示:主要是仿照QLCDNumber控件

#ifndef LCDNUMBERITEM_H
#define LCDNUMBERITEM_H
 
#include <QtQuick/QQuickPaintedItem>
#include <QBitArray>
class LCDNumberItem :  public QQuickPaintedItem
{
    Q_OBJECT
    Q_PROPERTY(bool smallDecimalPoint READ smallDecimalPoint WRITE setSmallDecimalPoint)
    Q_PROPERTY(int digitCount READ digitCount WRITE setDigitCount)
    Q_PROPERTY(Mode mode READ mode WRITE setMode)
    Q_PROPERTY(SegmentStyle segmentStyle READ segmentStyle WRITE setSegmentStyle)
    Q_PROPERTY(double value READ value WRITE display)
    Q_PROPERTY(int intValue READ intValue WRITE display)
public:
     LCDNumberItem(QQuickItem *parent = 0);
 
     ~LCDNumberItem();
     enum Mode {
         Hex, Dec, Oct, Bin
     };
     Q_ENUM(Mode)
     enum SegmentStyle {
        Outline , Filled, Flat
     };
     Q_ENUM(SegmentStyle)
     bool smallDecimalPoint() const;
     int digitCount() const;
     void setDigitCount(int nDigits);
 
     bool checkOverflow(double num) const;
     bool checkOverflow(int num) const;
 
     Mode mode() const;
     void setMode(Mode);
 
     SegmentStyle segmentStyle() const;
     void setSegmentStyle(SegmentStyle);
 
     double value() const;
     int intValue() const;
     void paint(QPainter *painter);
 
public Q_SLOTS:
    void display(const QString &str);
    void display(int num);
    void display(double num);
    void setHexMode();
    void setDecMode();
    void setOctMode();
    void setBinMode();
    void setSmallDecimalPoint(bool);
signals:
    void overflow();
public slots:
private:
    void init();
    void internalSetString(const QString& s);
    void drawString(const QString& s, QPainter &, QBitArray * = 0, bool = true);
    void drawDigit(const QPoint &, QPainter &, int, char, char = ' ');
    void drawSegment(const QPoint &, char, QPainter &, int, bool = false);
 
private:
    int ndigits;
    double val;
    uint base : 2;
    uint smallPoint : 1;
    uint fill : 1;
    uint shadow : 1;
    QString digitStr;
    QBitArray points;
};
 
#endif // LCDNUMBERITEM_H
 

实现文件基本和QLCDNumber控件差不多,本人还在完善中,争取实现更换颜色。在使用之前要注册一下:

qmlRegisterType<LCDNumberItem>("LCDNumberItem", 1, 0, "LCDNumberItem");

初步显示效果如下: