cardsview.cpp

来自「程序代码使用说明: (1)所有源代码目录下都提供了Makefile(非Qt)」· C++ 代码 · 共 105 行

CPP
105
字号
#include "CardsView.h"#include "CardsModel.h"#include "CardsDelegate.h"#include <QHeaderView>#include <QMenu>#include <QKeyEvent>#include <QMouseEvent>#include <QMessageBox>CardsView::CardsView(QWidget *parent) : QTableView(parent){    setFrameStyle(NoFrame);    verticalHeader()->hide();    horizontalHeader()->hide();    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);}void CardsView::resizeEvent(QResizeEvent *e){    Q_UNUSED(e);    int cell_w = contentsRect().width() / model()->columnCount();    int cell_h = contentsRect().height() / model()->rowCount();    CardsDelegate::cellSize = QSize(cell_w, cell_h);    // Calculate border polygon, 2% for border    int x_offset = cell_w - int(cell_w * 0.98);     int y_offset = cell_h - int(cell_h * 0.98);    CardsDelegate::border.setPoints(6,    0, 0,    cell_w, 0,    cell_w - x_offset, y_offset,    x_offset, y_offset,    x_offset, cell_h - y_offset,    0, cell_h);    int i;    for (i = 0; i < model()->rowCount(); ++i)        verticalHeader()->resizeSection(i, cell_h);    for (i = 0; i < model()->columnCount(); ++i)        horizontalHeader()->resizeSection(i, cell_w);}void CardsView::keyPressEvent(QKeyEvent* e){    CardsModel *pt = qobject_cast<CardsModel *>(model());    if (!pt)     {        QTableView::keyPressEvent(e);        return;    }    switch ( e->key() )     {        case Qt::Key_Up: pt->moveUp(); e->accept(); break;        case Qt::Key_Down: pt->moveDown(); e->accept(); break;        case Qt::Key_Left:            {                pt->moveLeft();                e->accept();                break;            }        case Qt::Key_Right:            {                pt->moveRight();                e->accept();                break;            }        default:            QTableView::keyPressEvent(e);        return;    }}void CardsView::setModel(QAbstractItemModel *m){    QTableView::setModel(m);    CardsModel *pt = qobject_cast<CardsModel *>(model());    if (pt)        connect(pt, SIGNAL(gameWon()), this, SLOT(announceWin()));}void CardsView::mousePressEvent(QMouseEvent* e){    CardsModel *pt = qobject_cast<CardsModel *>(model());    if (!pt) {        QTableView::mousePressEvent(e);        return;    }    pt->move( indexAt( QPoint( e->x(), e->y() ) ) );}void CardsView::announceWin(){    QMessageBox::information(this,         "Congratulations!", "You win the game!");}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?