【5】QT布尔表达式模型

近日天气寒冷,学习的热情都快被这气温给打压下去,早晨起不来,晚上又想早点躺在被窝里面,这样下去,感觉整个人如同咸鱼一般。无决心者,然小事可扰之,坐立不安,思前想后,时不待也,欲成事之,必静之以练其心智,久而久之,不成难矣!

//booleanmodel.h
#ifndef BOOLEANMODEL_H
#define BOOLEANMODEL_H
#include "node.h"
#include <QAbstractItemModel>

class Node;

class BooleanModel:public QAbstractItemModel
{
public:
    BooleanModel(QObject *parent=0);
    ~BooleanModel();

    void setRootNode(Node *node);

    QModelIndex index(int row,int column,const QModelIndex &parent)const;
    QModelIndex parent(const QModelIndex &child)const;

    int rowCount(const QModelIndex &parent) const;
    int columnCount(const QModelIndex &parent) const;
    QVariant data(const QModelIndex &index,int role) const;
    QVariant headerData(int section,Qt::Orientation orientation,int role) const;

private:
    Node *nodeFromIndex(const QModelIndex &index)const;

    Node *rootNode;
};

#endif // BOOLEANMODEL_H
//booleanparser.h
#ifndef BOOLEAMPARSER_H
#define BOOLEAMPARSER_H
#include "node.h"

class BooleanParser
{
public:
    Node *parse(const QString &expr);

private:
    Node *parseOrExpression();
    Node *parseAndExpression();
    Node *parseNotExpression();
    Node *parseAtom();
    Node *parseIdentifier();
    void addChild(Node *parent,Node *child);
    void addToken(Node *parent,const QString &str,Node::Type type);
    bool matchToken(const QString &str) const;

    QString in;
    int pos;
};

#endif // BOOLEANPARSER_H
//booleanwindow.h
#ifndef BOOLEANWINDOW_H
#define BOOLEANWINDOW_H
#include <QWidget>

class QLabel;
class QLineEdit;
class QTreeView;
class BooleanModel;

class BooleanWindow:public QWidget
{
    Q_OBJECT
public:
    BooleanWindow();
private slots:
    void booleanExpressionChanged(const QString &expr);
private:
    QLabel *label;
    QLineEdit *lineEdit;
    BooleanModel *booleanModel;
    QTreeView *treeView;
};

#endif // BOOLEANWINDOW_H
//node.h
#ifndef NODE_H
#define NODE_H
#include <QString>
#include <QList>

//node类为树的节点
class Node
{
public:
    enum Type{Root,OrExpression,AndExpression,NotExpression,Atom,Identifier,Operator,Punctuator};
    Node(Type type,const QString &str="");
    ~Node();

    Type type;//类型是否为操作符
    QString str;//存数据
    Node *parent;//指向父节点
    QList<Node *> children;//保存node所有节点
};

#endif // NODE_H
//booleanmodel.cpp
#include "booleanmodel.h"

BooleanModel::BooleanModel(QObject *parent):QAbstractItemModel(parent)
{
    rootNode=0;
}

BooleanModel::~BooleanModel()
{
    delete rootNode;
}

void BooleanModel::setRootNode(Node *node)
{
    beginResetModel();
    delete rootNode;
    rootNode=node;
    endResetModel();
}

//返回第row行,第column列,父节点为parent的元素QModelIndex对象
QModelIndex BooleanModel::index(int row, int column, const QModelIndex &parent) const
{
    if(!rootNode||row<0||column<0)
        return QModelIndex();
    Node *parentNode=nodeFromIndex(parent);
    Node *childNode=parentNode->children.value(row);
    if(!childNode)
        return QModelIndex();
    return createIndex(row,column,childNode);
}

int BooleanModel::rowCount(const QModelIndex &parent) const
{
    if(parent.column()>0){
        return 0;
    }
    Node *parentNode =nodeFromIndex(parent);
    if(!parentNode)
        return 0;
    return parentNode->children.count();
}

int BooleanModel::columnCount(const QModelIndex &) const
{
    return 2;
}

//返回子节点所属的父节点的索引
QModelIndex BooleanModel::parent(const QModelIndex &child)const
{
    Node *node=nodeFromIndex(child);
    if(!node)
        return QModelIndex();
    Node *parentNode=node->parent;
    if(!parentNode)
        return QModelIndex();
    Node *grandparentNode=parentNode->parent;
    if(!grandparentNode)
        return QModelIndex();

    int row=grandparentNode->children.indexOf(parentNode);
    return createIndex(row,0,parentNode);
}

//返回单元格的显示值
QVariant BooleanModel::data(const QModelIndex &index, int role) const
{
    if(role!=Qt::DisplayRole)
        return QVariant();
    Node *node=nodeFromIndex(index);
    if(!node)
        return QVariant();

    if(index.column()==0){
        switch (node->type){
        case Node::Root:
            return tr("Root");
        case Node::OrExpression:
            return tr("OR Expression");
        case Node::AndExpression:
            return tr("AND Expression");
        case Node::NotExpression:
            return tr("NOT Expression");
        case Node::Atom:
            return tr("Atom");
        case Node::Identifier:
            return tr("Identifier");
        case Node::Operator:
            return tr("Operator");
        case Node::Punctuator:
            return tr("Punctuator");
        default:
            return tr("Unknown");
        }
    }else if(index.column()==1){
        return node->str;
    }
    return QVariant();
}

QVariant BooleanModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(orientation==Qt::Horizontal&&role==Qt::DisplayRole){
        if(section==0){
            return tr("Node");
        }else if(section==1){
            return tr("Value");
        }
    }
    return QVariant();
}

Node *BooleanModel::nodeFromIndex(const QModelIndex &index) const
{
    if(index.isValid()){
        return static_cast<Node *>(index.internalPointer());
    }else{
        return rootNode;
    }
}
//booleanparser.cpp
#include "booleanparser.h"

Node *BooleanParser::parse(const QString &expr)
{
    in=expr;
    in.replace(" ","");
    pos=0;//当前字符的位置

    //创建根节点
    Node *node=new Node(Node::Root);
    addChild(node,parseOrExpression());
    return node;
}
//布尔表达式not and or优先级从高到低
//递归下降算法
Node *BooleanParser::parseOrExpression()
{
    Node *childNode=parseAndExpression();
    if(matchToken("||")){
        Node *node=new Node(Node::OrExpression);
        addChild(node,childNode);
        while(matchToken("||")){
            addToken(node,"||",Node::Operator);
            addChild(node,parseAndExpression());
        }
        return node;
    }else{
        return childNode;
    }
}

Node *BooleanParser::parseAndExpression()
{
    Node *childNode=parseNotExpression();
    if(matchToken("&&")){
        Node *node=new Node(Node::AndExpression);
        addChild(node,childNode);
        while(matchToken("&&")){
            addToken(node,"&&",Node::Operator);
            addChild(node,parseNotExpression());
        }
        return node;
    }else{
        return childNode;
    }
}

Node *BooleanParser::parseNotExpression()
{
    if(matchToken("!")){
        Node *node=new Node(Node::NotExpression);
        while(matchToken("!"))
            addToken(node,"!",Node::Operator);
        addChild(node,parseAtom());
        return node;
    }else{
        return parseAtom();
    }
}

Node *BooleanParser::parseAtom()
{
    if(matchToken("(")){
        Node *node=new Node(Node::Atom);
        addToken(node,"(",Node::Punctuator);
        addChild(node,parseOrExpression());
        addToken(node,")",Node::Punctuator);
        return node;
    }else{
        return parseIdentifier();
    }
}

Node *BooleanParser::parseIdentifier()
{
    int startPos=pos;
    while(pos<in.length()&&in[pos].isLetterOrNumber())
        ++pos;
    if(pos>startPos){
        return new Node(Node::Identifier,in.mid(startPos,pos-startPos));
    }else{
        return 0;
    }
}

void BooleanParser::addChild(Node *parent, Node *child)
{
    if(child){
        parent->children+=child;
        parent->str+=child->str;
        child->parent=parent;
    }
}

void BooleanParser::addToken(Node *parent, const QString &str, Node::Type type)
{
    if(in.mid(pos,str.length())==str){
        addChild(parent,new Node(type,str));
        pos+=str.length();
    }
}

bool BooleanParser::matchToken(const QString &str) const
{
    return in.mid(pos,str.length())==str;
}
//booleanwindow.cpp
#include <QtGui>
#include <QtWidgets>

#include "booleanmodel.h"
#include "booleanparser.h"
#include "booleanwindow.h"

BooleanWindow::BooleanWindow()
{
    label=new QLabel(tr("Boolean expression"));
    lineEdit =new QLineEdit;

    booleanModel=new BooleanModel(this);
    treeView=new QTreeView;
    treeView->setModel(booleanModel);

    connect(lineEdit,SIGNAL(textChanged(const QString &)),this,SLOT(booleanExpressionChanged(const QString &)));

    QGridLayout *layout=new QGridLayout;
    layout->addWidget(label,0,0);
    layout->addWidget(lineEdit,0,1);
    layout->addWidget(treeView,1,0,1,2);
    setLayout(layout);

    setWindowTitle(tr("Boolean Parser"));
}

void BooleanWindow::booleanExpressionChanged(const QString &expr)
{
    BooleanParser parser;
    Node *rootNode=parser.parse(expr);
    booleanModel->setRootNode(rootNode);
}
//main.cpp
#include <QApplication>
#include "booleanwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    BooleanWindow window;
    window.show();
    return a.exec();
}
//node.cpp
#include "node.h"
Node::Node(Type type,const QString &str)
{
    this->type=type;
    this->str=str;
    parent=0;
}

Node::~Node()
{
   qDeleteAll(children);//删除所有元素,参数必为指针类型,调用后指针不会赋值为零
}

备注:QT错误undefined reference to vtable for **,解决办法删除debug下面的Makefile文件,我自己是将编译后的文件全部删除后,重新编译就可以了,原因是添加Q_OBJECT宏之后,没有经过qt解析信号与槽相关部分,导致编译器编译出错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值