CommonData.h
#ifndef COMMONDATA_H
#define COMMONDATA_H
enum class PressKeyType{
UP,
DOWM,
LEFT,//向前翻页至第一页
RIGHT//向后翻页至最后一页
};
#endif // COMMONDATA_H
customtablewidget.h
#ifndef CUSTOMTABLEWIDGET_H
#define CUSTOMTABLEWIDGET_H
#include "CommonData.h"
#include <QTableWidget>
class CustomTableWidget : public QTableWidget
{
Q_OBJECT
public:
CustomTableWidget(QWidget *parent = nullptr);
protected:
void keyPressEvent(QKeyEvent *event) override;
void paintEvent(QPaintEvent *) override;
signals:
void signUpdateClass(const int& index,const PressKeyType &pressType);
};
#endif // CUSTOMTABLEWIDGET_H
customtablewidget.cpp
#include "customtablewidget.h"
#include <QKeyEvent>
#include <QPainter>
CustomTableWidget::CustomTableWidget(QWidget *parent):QTableWidget(parent)
{
}
void CustomTableWidget::keyPressEvent(QKeyEvent *event)
{
int nCurRow = currentRow();
int nCurCol = currentColumn();
if(event->key() == Qt::Key_Up){
if(nCurRow != 0){
currentItem()->setBackgroundColor(Qt::transparent);
nCurRow -= 1;
setCurrentCell(nCurRow,nCurCol);
emit signUpdateClass(nCurRow,PressKeyType::UP);
}
}else if(event->key() == Qt::Key_Down){
if(nCurRow != rowCount() -1){
currentItem()->setBackgroundColor(Qt::transparent);
nCurRow += 1;
setCurrentCell(nCurRow,nCurCol);
emit signUpdateClass(nCurRow,PressKeyType::DOWM);
}
}else if(event->key() == Qt::Key_Left){
currentItem()->setBackgroundColor(Qt::transparent);
setCurrentCell(0,0);
emit signUpdateClass(0,PressKeyType::LEFT);
}else if(event->key() == Qt::Key_Right){
currentItem()->setBackgroundColor(Qt::transparent);
setCurrentCell(rowCount()-1,0);
emit signUpdateClass(rowCount()-1,PressKeyType::RIGHT);
}else{
QTableWidget::keyPressEvent(event);
}
}
void CustomTableWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
//设置选中项的背景色
QTableWidgetItem *newItem = this->currentItem();
if (newItem) {
newItem->setBackground(QBrush(Qt::blue));
}
QTableWidget::paintEvent(event);
}
dowmarrowlabel.h
#ifndef DOWNARROWLABEL_H
#define DOWNARROWLABEL_H
#include <QLabel>
class DownArrowLabel:public QLabel
{
public:
DownArrowLabel(QWidget* parent = nullptr);
protected:
void paintEvent(QPaintEvent *) override;
};
#endif // DOWNARROWLABEL_H
dowmarrowlabel.cpp
#include "downarrowlabel.h"
#include <QPainter>
#include <QtMath>//qSqrt()
DownArrowLabel::DownArrowLabel(QWidget *parent):QLabel(parent)
{
setFixedSize(20,20);
}
void DownArrowLabel::paintEvent(QPaintEvent *event)
{
QLabel::paintEvent(event); // 调用基类的paintEvent进行常规绘制(如果有的话)
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿
// 设置画笔和画刷
painter.setPen(Qt::NoPen); // 无边框
painter.setBrush(Qt::yellow); // 黄色填充
// 确定等边三角形的边长