diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..f95ff5f --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,60 @@ +--- +Checks: '-*,clang-analyzer-*,readability-*,performance-*,modernize-*,bugprone-*,cert-,cppcoreguidelines-,portability-*,llvm-*,google-*' +WarningsAsErrors: '' +HeaderFilterRegex: '.' +AnalyzeTemporaryDtors: false +FormatStyle: file +User: user +CheckOptions: + - key: readability-identifier-naming.AbstractClassCase + value: CamelCase + - key: readability-identifier-naming.ClassCase + value: CamelCase + - key: readability-identifier-naming.ClassConstantCase + value: UPPER_CASE + - key: readability-identifier-naming.ClassConstantPrefix + value: 'k' + - key: readability-identifier-naming.ClassMemberCase + value: lower_case + - key: readability-identifier-naming.ClassMemberPrefix + value: 'm_' + - key: readability-identifier-naming.ClassMethodCase + value: camelBack + - key: readability-identifier-naming.ConstexprVariableCase + value: UPPER_CASE + - key: readability-identifier-naming.ConstexprVariablePrefix + value: 'k' + - key: readability-identifier-naming.EnumCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantCase + value: UPPER_CASE + - key: readability-identifier-naming.EnumConstantPrefix + value: '' + - key: readability-identifier-naming.FunctionCase + value: camelBack + - key: readability-identifier-naming.FunctionParameterCase + value: lower_case + - key: readability-identifier-naming.GlobalConstantCase + value: UPPER_CASE + - key: readability-identifier-naming.GlobalConstantPrefix + value: 'k' + - key: readability-identifier-naming.GlobalFunctionCase + value: camelBack + - key: readability-identifier-naming.GlobalVariableCase + value: lower_case + - key: readability-identifier-naming.GlobalVariablePrefix + value: 'g_' + - key: readability-identifier-naming.InlineNamespaceCase + value: lower_case + - key: readability-identifier-naming.LocalConstantCase + value: UPPER_CASE + - key: readability-identifier-naming.LocalConstantPrefix + value: 'k' + - key: readability-identifier-naming.LocalVariableCase + value: lower_case + - key: readability-identifier-naming.MacroDefinitionCase + value: UPPER_CASE + - key: readability-identifier-naming.NamespaceCase + value: lower_case + - key: bugprone-narrowing-conversions.IgnoreFloatingPointPrecisionLoss + value: 'false' diff --git a/Battery/batterywidget.cpp b/Battery/batterywidget.cpp index 7e2f881..52305e9 100644 --- a/Battery/batterywidget.cpp +++ b/Battery/batterywidget.cpp @@ -25,9 +25,7 @@ BatteryWidget::BatteryWidget(QWidget *parent) connect(this, &BatteryWidget::valueChanged, this, &BatteryWidget::onStartAnimation); } -BatteryWidget::~BatteryWidget() -{ -} +BatteryWidget::~BatteryWidget() = default; void BatteryWidget::setBorderColor(const QColor &color) { @@ -35,7 +33,7 @@ void BatteryWidget::setBorderColor(const QColor &color) update(); } -QColor BatteryWidget::borderColor() const +auto BatteryWidget::borderColor() const -> QColor { return d_ptr->borderColor; } @@ -46,7 +44,7 @@ void BatteryWidget::setPowerColor(const QColor &color) update(); } -QColor BatteryWidget::powerColor() const +auto BatteryWidget::powerColor() const -> QColor { return d_ptr->powerColor; } @@ -57,19 +55,19 @@ void BatteryWidget::setAlarmColor(const QColor &color) update(); } -QColor BatteryWidget::alarmColor() const +auto BatteryWidget::alarmColor() const -> QColor { return d_ptr->alarmColor; } -QSize BatteryWidget::sizeHint() const +auto BatteryWidget::sizeHint() const -> QSize { - return QSize(150, 80); + return {150, 80}; } -QSize BatteryWidget::minimumSizeHint() const +auto BatteryWidget::minimumSizeHint() const -> QSize { - return QSize(80, 45); + return {80, 45}; } void BatteryWidget::paintEvent(QPaintEvent *event) @@ -99,8 +97,9 @@ void BatteryWidget::paintEvent(QPaintEvent *event) void BatteryWidget::onStartAnimation(const int value) { - if (value == d_ptr->value) + if (value == d_ptr->value) { return; + } int start = d_ptr->value; int end = value; @@ -110,22 +109,20 @@ void BatteryWidget::onStartAnimation(const int value) d_ptr->animation->start(); } -int BatteryWidget::value() const +auto BatteryWidget::value() const -> int { return d_ptr->value; } -void BatteryWidget::setValue(const int value) +void BatteryWidget::setValue(int value) { - if (value == d_ptr->value) + Q_ASSERT(value >= 0 && value <= 100); + + if (value == d_ptr->value) { return; + } - if(value < 0) - d_ptr->value = 0; - else if(value > 100) - d_ptr->value = 100; - else - d_ptr->value = value; + d_ptr->value = value; update(); } @@ -144,8 +141,7 @@ void BatteryWidget::drawPower(QPainter *painter, const QRectF &batteryRect, cons double margin = qMin(width(), height()) / 50.0; margin = qMax(margin, linew); qreal unit = (batteryRect.width() - (margin * 2)) / 100; - QPointF topLeft(batteryRect.topLeft().x() + margin, - batteryRect.topLeft().y() + margin); + QPointF topLeft(batteryRect.topLeft().x() + margin, batteryRect.topLeft().y() + margin); QPointF bottomRight(d_ptr->value * unit + margin + 5, batteryRect.bottomRight().y() - margin); QRectF rect(topLeft, bottomRight); double bgRadius = rect.height() / 30; diff --git a/Battery/batterywidget.h b/Battery/batterywidget.h index 462394f..942cd5c 100644 --- a/Battery/batterywidget.h +++ b/Battery/batterywidget.h @@ -12,35 +12,35 @@ class BatteryWidget : public QWidget Q_PROPERTY(QColor alarmColor READ alarmColor WRITE setAlarmColor) public: explicit BatteryWidget(QWidget *parent = nullptr); - ~BatteryWidget(); + ~BatteryWidget() override; - QSize sizeHint() const override; - QSize minimumSizeHint() const override; + [[nodiscard]] [[nodiscard]] auto sizeHint() const -> QSize override; + [[nodiscard]] [[nodiscard]] auto minimumSizeHint() const -> QSize override; - void setBorderColor(const QColor& color); - QColor borderColor() const; + void setBorderColor(const QColor &color); + [[nodiscard]] [[nodiscard]] auto borderColor() const -> QColor; - void setPowerColor(const QColor& color); - QColor powerColor() const; + void setPowerColor(const QColor &color); + [[nodiscard]] [[nodiscard]] auto powerColor() const -> QColor; - void setAlarmColor(const QColor& color); - QColor alarmColor() const; + void setAlarmColor(const QColor &color); + [[nodiscard]] [[nodiscard]] auto alarmColor() const -> QColor; - void setValue(const int value); - int value() const; + void setValue(int value); + [[nodiscard]] [[nodiscard]] auto value() const -> int; signals: - void valueChanged(const int value); + void valueChanged(int value); private slots: - void onStartAnimation(const int value); + void onStartAnimation(int value); protected: void paintEvent(QPaintEvent *event) override; private: - void drawBorder(QPainter *painter, const QRectF &batteryRect, const double linew); - void drawPower(QPainter *painter, const QRectF &batteryRect, const double linew); + void drawBorder(QPainter *painter, const QRectF &batteryRect, double linew); + void drawPower(QPainter *painter, const QRectF &batteryRect, double linew); void drawValue(QPainter *painter, const QRectF &batteryRect); void drawHeader(QPainter *painter, const QRectF &batteryRect); diff --git a/Battery/main.cpp b/Battery/main.cpp index fd3e533..24ba3b6 100644 --- a/Battery/main.cpp +++ b/Battery/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/Battery/mainwindow.cpp b/Battery/mainwindow.cpp index 6344b62..c14910d 100644 --- a/Battery/mainwindow.cpp +++ b/Battery/mainwindow.cpp @@ -19,7 +19,4 @@ MainWindow::MainWindow(QWidget *parent) resize(300, 160); } -MainWindow::~MainWindow() -{ -} - +MainWindow::~MainWindow() {} diff --git a/Battery/mainwindow.h b/Battery/mainwindow.h index eb5f430..ffddf4a 100644 --- a/Battery/mainwindow.h +++ b/Battery/mainwindow.h @@ -8,6 +8,6 @@ class MainWindow : public QMainWindow Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + ~MainWindow() override; }; #endif // MAINWINDOW_H diff --git a/BubbleWindow/bubblewidget.cpp b/BubbleWindow/bubblewidget.cpp index 150b485..03fe409 100644 --- a/BubbleWindow/bubblewidget.cpp +++ b/BubbleWindow/bubblewidget.cpp @@ -2,7 +2,8 @@ #include -struct Triangle{ +struct Triangle +{ int width = 10; int height = 10; BubbleWidget::Direction direct = BubbleWidget::Direction::Top; @@ -12,17 +13,20 @@ class BubbleWidget::BubbleWidgetPrivate { public: BubbleWidgetPrivate(QWidget *parent) - : owner(parent){ - shadowEffect = new QGraphicsDropShadowEffect(owner); + : q_ptr(parent) + { + shadowEffect = new QGraphicsDropShadowEffect(q_ptr); shadowEffect->setOffset(0, 0); shadowEffect->setColor(Qt::gray); shadowEffect->setBlurRadius(shadowWidth); - centralWidget = new QWidget(owner); + centralWidget = new QWidget(q_ptr); pen.setWidth(2); } - QWidget *owner; - QGraphicsDropShadowEffect* shadowEffect; + + QWidget *q_ptr; + + QGraphicsDropShadowEffect *shadowEffect; QWidget *centralWidget; Triangle triangle; @@ -45,10 +49,7 @@ BubbleWidget::BubbleWidget(QWidget *parent) resize(200, 100); } -BubbleWidget::~BubbleWidget() -{ - -} +BubbleWidget::~BubbleWidget() {} void BubbleWidget::setPen(const QPen &pen) { @@ -142,25 +143,28 @@ void BubbleWidget::paintEvent(QPaintEvent *) QPainterPath drawPath; QPolygon trianglePolygon; QRect rect; - switch (d_ptr->triangle.direct) - { + switch (d_ptr->triangle.direct) { case Top: trianglePolygon << QPoint(width() / 2, d_ptr->shadowWidth); trianglePolygon << QPoint(width() / 2 + d_ptr->triangle.width / 2, d_ptr->triangle.height + d_ptr->shadowWidth); trianglePolygon << QPoint(width() / 2 - d_ptr->triangle.width / 2, d_ptr->triangle.height + d_ptr->shadowWidth); - rect = QRect(d_ptr->shadowWidth, d_ptr->triangle.height + d_ptr->shadowWidth, + rect = QRect(d_ptr->shadowWidth, + d_ptr->triangle.height + d_ptr->shadowWidth, width() - d_ptr->shadowWidth * 2, height() - d_ptr->shadowWidth * 2 - d_ptr->triangle.height); drawPath.addRoundedRect(rect, d_ptr->borderRadius, d_ptr->borderRadius); break; case Left: - trianglePolygon << QPoint(d_ptr->shadowWidth, d_ptr->triangle.height + d_ptr->shadowWidth + d_ptr->shadowWidth); - trianglePolygon << QPoint(d_ptr->shadowWidth + d_ptr->triangle.width, d_ptr->shadowWidth + d_ptr->shadowWidth); + trianglePolygon << QPoint(d_ptr->shadowWidth, + d_ptr->triangle.height + d_ptr->shadowWidth + d_ptr->shadowWidth); + trianglePolygon << QPoint(d_ptr->shadowWidth + d_ptr->triangle.width, + d_ptr->shadowWidth + d_ptr->shadowWidth); trianglePolygon << QPoint(d_ptr->shadowWidth + d_ptr->triangle.width, d_ptr->triangle.height + d_ptr->shadowWidth + d_ptr->shadowWidth); - rect = QRect(d_ptr->shadowWidth + d_ptr->triangle.width, d_ptr->shadowWidth, + rect = QRect(d_ptr->shadowWidth + d_ptr->triangle.width, + d_ptr->shadowWidth, width() - d_ptr->shadowWidth * 2 - d_ptr->triangle.width, height() - d_ptr->shadowWidth * 2); drawPath.addRoundedRect(rect, d_ptr->borderRadius, d_ptr->borderRadius); @@ -172,7 +176,8 @@ void BubbleWidget::paintEvent(QPaintEvent *) d_ptr->triangle.height + d_ptr->shadowWidth + d_ptr->shadowWidth); trianglePolygon << QPoint(width() - d_ptr->shadowWidth, d_ptr->triangle.height + d_ptr->shadowWidth + d_ptr->shadowWidth); - rect = QRect(d_ptr->shadowWidth, d_ptr->shadowWidth, + rect = QRect(d_ptr->shadowWidth, + d_ptr->shadowWidth, width() - d_ptr->shadowWidth * 2 - d_ptr->triangle.width, height() - d_ptr->shadowWidth * 2); drawPath.addRoundedRect(rect, d_ptr->borderRadius, d_ptr->borderRadius); @@ -184,7 +189,9 @@ void BubbleWidget::paintEvent(QPaintEvent *) height() - d_ptr->shadowWidth - d_ptr->triangle.height); trianglePolygon << QPoint(width() / 2 - d_ptr->triangle.width / 2, height() - d_ptr->shadowWidth - d_ptr->triangle.height); - rect = QRect(d_ptr->shadowWidth, d_ptr->shadowWidth, width() - d_ptr->shadowWidth * 2, + rect = QRect(d_ptr->shadowWidth, + d_ptr->shadowWidth, + width() - d_ptr->shadowWidth * 2, height() - d_ptr->shadowWidth * 2 - d_ptr->triangle.height); drawPath.addRoundedRect(rect, d_ptr->borderRadius, d_ptr->borderRadius); break; @@ -193,8 +200,6 @@ void BubbleWidget::paintEvent(QPaintEvent *) drawPath = drawPath.simplified(); painter.drawPath(drawPath); - - painter.setFont(QFont("Microsoft YaHei", 11, 500)); rect = rect.adjusted(5, 5, -5, -5); painter.drawText(rect, Qt::AlignCenter, d_ptr->text); diff --git a/BubbleWindow/bubblewidget.h b/BubbleWindow/bubblewidget.h index cabe1e1..32431d6 100644 --- a/BubbleWindow/bubblewidget.h +++ b/BubbleWindow/bubblewidget.h @@ -7,31 +7,31 @@ class BubbleWidget : public QWidget { Q_OBJECT public: - enum Direction{ Left, Right, Top, Bottom }; + enum Direction { Left, Right, Top, Bottom }; explicit BubbleWidget(QWidget *parent = nullptr); ~BubbleWidget() override; void setPen(const QPen &pen); - QPen pen() const; + [[nodiscard]] auto pen() const -> QPen; void setBrush(const QBrush &brush); - QBrush brush() const; + [[nodiscard]] auto brush() const -> QBrush; void setShadowWidth(qint64 width); - qint64 shadowWidth(); + auto shadowWidth() -> qint64; void setBorderRadius(qint64 radius); - qint64 borderRadius(); + auto borderRadius() -> qint64; void setText(const QString &text); - QString text() const; + [[nodiscard]] auto text() const -> QString; // 设置小三角宽和高; void setTriangleInfo(int width, int height); void setDerection(Direction); - Direction direction(); + auto direction() -> Direction; void exec(); diff --git a/BubbleWindow/main.cpp b/BubbleWindow/main.cpp index fd3e533..24ba3b6 100644 --- a/BubbleWindow/main.cpp +++ b/BubbleWindow/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/Chart/CMakeLists.txt b/Chart/CMakeLists.txt index c87caf0..4f05fc7 100644 --- a/Chart/CMakeLists.txt +++ b/Chart/CMakeLists.txt @@ -1,31 +1,29 @@ set(PROJECT_SOURCES - main.cpp - mainwindow.cpp - mainwindow.h - areachart.h - areachart.cpp - callout.h - callout.cpp - chartlabel.h - chartlabel.cpp - chartview.h - chartview.cpp - datetimechart.h - datetimechart.cpp - dialogchart.h - dialogchart.cpp - dynamicchart.h - dynamicchart.cpp - dynamicchartx.h - dynamicchartx.cpp - linechart.h - linechart.cpp - normalchartdata.h - normalchartdata.cpp - piechart.h - piechart.cpp - stackedbarchart.h - stackedbarchart.cpp) + main.cpp + mainwindow.cpp + mainwindow.h + areachart.h + areachart.cpp + callout.h + callout.cpp + chartview.h + chartview.cpp + datetimechart.h + datetimechart.cpp + dialogchart.h + dialogchart.cpp + dynamicchart.h + dynamicchart.cpp + dynamicchartx.h + dynamicchartx.cpp + linechart.h + linechart.cpp + normalchartdata.h + normalchartdata.cpp + piechart.h + piechart.cpp + stackedbarchart.h + stackedbarchart.cpp) qt_add_executable(Chart MANUAL_FINALIZATION ${PROJECT_SOURCES}) target_link_libraries(Chart PRIVATE Qt6::Widgets Qt6::Charts) diff --git a/Chart/Chart.pro b/Chart/Chart.pro index 7925dcc..7baf4e6 100644 --- a/Chart/Chart.pro +++ b/Chart/Chart.pro @@ -18,7 +18,6 @@ DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ areachart.cpp \ callout.cpp \ - chartlabel.cpp \ chartview.cpp \ datetimechart.cpp \ dialogchart.cpp \ @@ -34,7 +33,6 @@ SOURCES += \ HEADERS += \ areachart.h \ callout.h \ - chartlabel.h \ chartview.h \ datetimechart.h \ dialogchart.h \ diff --git a/Chart/areachart.cpp b/Chart/areachart.cpp index 39e6e42..385ac29 100644 --- a/Chart/areachart.cpp +++ b/Chart/areachart.cpp @@ -4,10 +4,11 @@ class AreaChart::AreaChartPrivate { public: - AreaChartPrivate(ChartView *parent) - :owner(parent){ - areaSeries = new QAreaSeries(owner); - scatterSeries = new QScatterSeries(owner); + explicit AreaChartPrivate(ChartView *parent) + : q_ptr(parent) + { + areaSeries = new QAreaSeries(q_ptr); + scatterSeries = new QScatterSeries(q_ptr); scatterSeries->setMarkerSize(8); chart = new QChart; @@ -18,7 +19,9 @@ class AreaChart::AreaChartPrivate chart->axes(Qt::Horizontal).first()->setRange(0, 100); chart->axes(Qt::Vertical).first()->setRange(0, 100); } - ChartView *owner; + + ChartView *q_ptr; + QChart *chart; QAreaSeries *areaSeries; QScatterSeries *scatterSeries; @@ -31,9 +34,7 @@ AreaChart::AreaChart(QWidget *parent) setupUI(); } -AreaChart::~AreaChart() -{ -} +AreaChart::~AreaChart() = default; void AreaChart::setupUI() { @@ -44,7 +45,7 @@ void AreaChart::setupUI() QLineSeries *upperSeries = new QLineSeries(this); QLineSeries *lowerSeries = new QLineSeries(this); upperSeries->replace(pointList); - for(int i=0; ireplace(pointList); diff --git a/Chart/areachart.h b/Chart/areachart.h index f81b64b..6dfe3d7 100644 --- a/Chart/areachart.h +++ b/Chart/areachart.h @@ -7,7 +7,7 @@ class AreaChart : public ChartView { public: explicit AreaChart(QWidget *parent = nullptr); - ~AreaChart(); + ~AreaChart() override; private: void setupUI(); diff --git a/Chart/callout.cpp b/Chart/callout.cpp index bb37802..ba7cd24 100644 --- a/Chart/callout.cpp +++ b/Chart/callout.cpp @@ -28,19 +28,18 @@ ****************************************************************************/ #include "callout.h" -#include +#include #include -#include #include -#include +#include +#include -Callout::Callout(QChart *chart): - QGraphicsItem(chart), - m_chart(chart) -{ -} +Callout::Callout(QChart *chart) + : QGraphicsItem(chart) + , m_chart(chart) +{} -QRectF Callout::boundingRect() const +auto Callout::boundingRect() const -> QRectF { QPointF anchor = mapFromParent(m_chart->mapToPosition(m_anchor)); QRectF rect; @@ -76,16 +75,24 @@ void Callout::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, Q // get the nearest m_rect corner. qreal x = (onRight + rightOfCenter) * m_rect.width(); qreal y = (below + belowCenter) * m_rect.height(); - bool cornerCase = (above && onLeft) || (above && onRight) || (below && onLeft) || (below && onRight); + bool cornerCase = (above && onLeft) || (above && onRight) || (below && onLeft) + || (below && onRight); bool vertical = qAbs(anchor.x() - x) > qAbs(anchor.y() - y); - qreal x1 = x + leftOfCenter * 10 - rightOfCenter * 20 + cornerCase * !vertical * (onLeft * 10 - onRight * 20); - qreal y1 = y + aboveCenter * 10 - belowCenter * 20 + cornerCase * vertical * (above * 10 - below * 20);; + qreal x1 = x + leftOfCenter * 10 - rightOfCenter * 20 + + cornerCase * !vertical * (onLeft * 10 - onRight * 20); + qreal y1 = y + aboveCenter * 10 - belowCenter * 20 + + cornerCase * vertical * (above * 10 - below * 20); + ; point1.setX(x1); point1.setY(y1); - qreal x2 = x + leftOfCenter * 20 - rightOfCenter * 10 + cornerCase * !vertical * (onLeft * 20 - onRight * 10);; - qreal y2 = y + aboveCenter * 20 - belowCenter * 10 + cornerCase * vertical * (above * 20 - below * 10);; + qreal x2 = x + leftOfCenter * 20 - rightOfCenter * 10 + + cornerCase * !vertical * (onLeft * 20 - onRight * 10); + ; + qreal y2 = y + aboveCenter * 20 - belowCenter * 10 + + cornerCase * vertical * (above * 20 - below * 10); + ; point2.setX(x2); point2.setY(y2); @@ -106,7 +113,7 @@ void Callout::mousePressEvent(QGraphicsSceneMouseEvent *event) void Callout::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { - if (event->buttons() & Qt::LeftButton){ + if (event->buttons() & Qt::LeftButton) { setPos(mapToParent(event->pos() - event->buttonDownPos(Qt::LeftButton))); event->setAccepted(true); } else { diff --git a/Chart/callout.h b/Chart/callout.h index ddc444d..39c0fae 100644 --- a/Chart/callout.h +++ b/Chart/callout.h @@ -31,8 +31,8 @@ #define CALLOUT_H #include -#include #include +#include QT_BEGIN_NAMESPACE class QGraphicsSceneMouseEvent; @@ -49,12 +49,12 @@ class Callout : public QGraphicsItem void setAnchor(QPointF point); void updateGeometry(); - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget); + [[nodiscard]] auto boundingRect() const -> QRectF override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); - void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; private: QString m_text; diff --git a/Chart/chartlabel.cpp b/Chart/chartlabel.cpp deleted file mode 100644 index 182c3fb..0000000 --- a/Chart/chartlabel.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "chartlabel.h" - -ChartLabel::ChartLabel(QChart *parent) - : QGraphicsItem(parent) -{ - -} diff --git a/Chart/chartlabel.h b/Chart/chartlabel.h deleted file mode 100644 index b35929e..0000000 --- a/Chart/chartlabel.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef CHARTLABEL_H -#define CHARTLABEL_H - -#include - -class ChartLabel : public QGraphicsItem -{ -public: - explicit ChartLabel(QChart *parent); -}; - -#endif // CHARTLABEL_H diff --git a/Chart/chartview.cpp b/Chart/chartview.cpp index db67de8..4c0b4d5 100644 --- a/Chart/chartview.cpp +++ b/Chart/chartview.cpp @@ -1,33 +1,18 @@ #include "chartview.h" ChartView::ChartView(QWidget *parent) - :QChartView(parent) -{ -} + : QChartView(parent) +{} void ChartView::keyPressEvent(QKeyEvent *event) { switch (event->key()) { - case Qt::Key_Plus: - chart()->zoomIn(); - break; - case Qt::Key_Minus: - chart()->zoomOut(); - break; - case Qt::Key_Left: - chart()->scroll(-1.0, 0); - break; - case Qt::Key_Right: - chart()->scroll(1.0, 0); - break; - case Qt::Key_Up: - chart()->scroll(0, 1.0); - break; - case Qt::Key_Down: - chart()->scroll(0, -1.0); - break; - default: - QGraphicsView::keyPressEvent(event); - break; + case Qt::Key_Plus: chart()->zoomIn(); break; + case Qt::Key_Minus: chart()->zoomOut(); break; + case Qt::Key_Left: chart()->scroll(-1.0, 0); break; + case Qt::Key_Right: chart()->scroll(1.0, 0); break; + case Qt::Key_Up: chart()->scroll(0, 1.0); break; + case Qt::Key_Down: chart()->scroll(0, -1.0); break; + default: QGraphicsView::keyPressEvent(event); break; } } diff --git a/Chart/datetimechart.cpp b/Chart/datetimechart.cpp index 54a5b29..c5def72 100644 --- a/Chart/datetimechart.cpp +++ b/Chart/datetimechart.cpp @@ -4,19 +4,19 @@ class DateTimeChart::DateTimeChartPrivate { public: - DateTimeChartPrivate(ChartView *parent) - : owner(parent) + explicit DateTimeChartPrivate(ChartView *parent) + : q_ptr(parent) { - dateTimeAxisX = new QDateTimeAxis(owner); + dateTimeAxisX = new QDateTimeAxis(q_ptr); dateTimeAxisX->setFormat("yyyy-MM"); //dateTimeAxisX->setTitleText(QObject::tr("Date")); - valueAxisY = new QValueAxis(owner); + valueAxisY = new QValueAxis(q_ptr); //valueAxisY->setTitleText(QObject::tr("Value")); valueAxisY->setRange(0, 100); - lineSeries = new QLineSeries(owner); - scatterSeries = new QScatterSeries(owner); + lineSeries = new QLineSeries(q_ptr); + scatterSeries = new QScatterSeries(q_ptr); scatterSeries->setMarkerSize(8); PointList pointList = generateRandomDataPoints(5, 101); @@ -42,7 +42,9 @@ class DateTimeChart::DateTimeChartPrivate scatterSeries->attachAxis(dateTimeAxisX); scatterSeries->attachAxis(valueAxisY); } - ChartView *owner; + + ChartView *q_ptr; + QChart *chart; QDateTimeAxis *dateTimeAxisX; QValueAxis *valueAxisY; @@ -57,9 +59,7 @@ DateTimeChart::DateTimeChart(QWidget *parent) setupUI(); } -DateTimeChart::~DateTimeChart() -{ -} +DateTimeChart::~DateTimeChart() = default; void DateTimeChart::setupUI() { diff --git a/Chart/datetimechart.h b/Chart/datetimechart.h index 9007a5a..84b857a 100644 --- a/Chart/datetimechart.h +++ b/Chart/datetimechart.h @@ -7,7 +7,7 @@ class DateTimeChart : public ChartView { public: explicit DateTimeChart(QWidget *parent = nullptr); - ~DateTimeChart(); + ~DateTimeChart() override; private: void setupUI(); diff --git a/Chart/dialogchart.cpp b/Chart/dialogchart.cpp index f576bc5..1723fdc 100644 --- a/Chart/dialogchart.cpp +++ b/Chart/dialogchart.cpp @@ -3,14 +3,14 @@ #include DialogChart::DialogChart(QGraphicsScene *scene, QWidget *parent) - :QDialog(parent) - ,m_scene(scene) + : QDialog(parent) + , m_scene(scene) { - view = new QChartView; - view->setRenderHint(QPainter::Antialiasing); - view->setScene(scene); + m_view = new QChartView; + m_view->setRenderHint(QPainter::Antialiasing); + m_view->setScene(scene); QHBoxLayout *layout = new QHBoxLayout(this); - layout->addWidget(view); + layout->addWidget(m_view); } void DialogChart::resizeEvent(QResizeEvent *event) @@ -18,8 +18,8 @@ void DialogChart::resizeEvent(QResizeEvent *event) qreal sx = event->size().width() / m_scene->width(); qreal sy = event->size().height() / m_scene->height(); qreal min = qMin(sx, sy); - view->scale(min, min); - view->show(); + m_view->scale(min, min); + m_view->show(); qDebug() << min; QDialog::resizeEvent(event); diff --git a/Chart/dialogchart.h b/Chart/dialogchart.h index a374622..237a322 100644 --- a/Chart/dialogchart.h +++ b/Chart/dialogchart.h @@ -13,7 +13,7 @@ class DialogChart : public QDialog void resizeEvent(QResizeEvent *) override; private: - QChartView *view; + QChartView *m_view; QGraphicsScene *m_scene; }; diff --git a/Chart/dynamicchart.cpp b/Chart/dynamicchart.cpp index 1accabe..f1d7303 100644 --- a/Chart/dynamicchart.cpp +++ b/Chart/dynamicchart.cpp @@ -3,9 +3,8 @@ class DynamicChart::DynamicChartPrivate { public: - DynamicChartPrivate(ChartView *parent) + explicit DynamicChartPrivate(ChartView *parent) : owner(parent) - , timerId(0) { splineSeries = new QSplineSeries(owner); scatterSeries = new QScatterSeries(owner); @@ -24,7 +23,7 @@ class DynamicChart::DynamicChartPrivate QChart *chart; QSplineSeries *splineSeries; QScatterSeries *scatterSeries; - int timerId; + int timerId = 0; QList data; }; @@ -36,9 +35,7 @@ DynamicChart::DynamicChart(QWidget *parent) startChart(); } -DynamicChart::~DynamicChart() -{ -} +DynamicChart::~DynamicChart() = default; void DynamicChart::timerEvent(QTimerEvent *event) { @@ -56,8 +53,9 @@ void DynamicChart::dataReceived(int value) d_ptr->data.removeFirst(); } - if (!isVisible()) + if (!isVisible()) { return; + } d_ptr->splineSeries->clear(); d_ptr->scatterSeries->clear(); diff --git a/Chart/dynamicchartx.cpp b/Chart/dynamicchartx.cpp index 8c4c968..2f8f886 100644 --- a/Chart/dynamicchartx.cpp +++ b/Chart/dynamicchartx.cpp @@ -1,15 +1,14 @@ #include "dynamicchartx.h" -class DynamicChartXPrivate{ +class DynamicChartX::DynamicChartXPrivate +{ public: - DynamicChartXPrivate(ChartView *parent) - : owner(parent) - , timerId(0) - , xValue(0) + explicit DynamicChartXPrivate(ChartView *parent) + : q_ptr(parent) { - valueAxis = new QValueAxis(owner); - splineSeries = new QSplineSeries(owner); - scatterSeries = new QScatterSeries(owner); + valueAxis = new QValueAxis(q_ptr); + splineSeries = new QSplineSeries(q_ptr); + scatterSeries = new QScatterSeries(q_ptr); scatterSeries->setMarkerSize(8); chart = new QChart; @@ -25,32 +24,30 @@ class DynamicChartXPrivate{ chart->axes(Qt::Vertical).first()->setRange(0, 100); } - ChartView *owner; + ChartView *q_ptr; + QChart *chart; QValueAxis *valueAxis; QSplineSeries *splineSeries; QScatterSeries *scatterSeries; - int timerId; + int timerId = 0; QList data; - qreal xValue; + qreal xValue = 0; }; DynamicChartX::DynamicChartX(QWidget *parent) : ChartView(parent) - , d(new DynamicChartXPrivate(this)) + , d_ptr(new DynamicChartXPrivate(this)) { setupChart(); startChart(); } -DynamicChartX::~DynamicChartX() -{ - delete d; -} +DynamicChartX::~DynamicChartX() = default; void DynamicChartX::timerEvent(QTimerEvent *event) { - if (event->timerId() == d->timerId) { + if (event->timerId() == d_ptr->timerId) { int newData = QRandomGenerator::global()->generate() % (100 + 1); dataReceived(newData); } @@ -58,29 +55,30 @@ void DynamicChartX::timerEvent(QTimerEvent *event) void DynamicChartX::dataReceived(int value) { - if(!isVisible()) + if (!isVisible()) { return; - qreal x = d->chart->plotArea().width() / 10; - d->splineSeries->append(d->xValue*100/10, value); - d->scatterSeries->append(d->xValue*100/10, value); - if(d->xValue > 10) - d->chart->scroll(x, 0); - d->xValue++; - if(d->splineSeries->points().size() > 10) - { - d->splineSeries->points().removeFirst(); - d->scatterSeries->points().removeFirst(); + } + qreal x = d_ptr->chart->plotArea().width() / 10; + d_ptr->splineSeries->append(d_ptr->xValue * 100 / 10, value); + d_ptr->scatterSeries->append(d_ptr->xValue * 100 / 10, value); + if (d_ptr->xValue > 10) { + d_ptr->chart->scroll(x, 0); + } + d_ptr->xValue++; + if (d_ptr->splineSeries->points().size() > 10) { + d_ptr->splineSeries->points().removeFirst(); + d_ptr->scatterSeries->points().removeFirst(); } } void DynamicChartX::startChart() { - d->timerId = startTimer(1000); + d_ptr->timerId = startTimer(1000); //QRandomGenerator::global()->seed(QDateTime::currentSecsSinceEpoch()); } void DynamicChartX::setupChart() { setRenderHint(QPainter::Antialiasing); - setChart(d->chart); + setChart(d_ptr->chart); } diff --git a/Chart/dynamicchartx.h b/Chart/dynamicchartx.h index 95cb911..74396e1 100644 --- a/Chart/dynamicchartx.h +++ b/Chart/dynamicchartx.h @@ -3,11 +3,10 @@ #include "chartview.h" -class DynamicChartXPrivate; class DynamicChartX : public ChartView { public: - DynamicChartX(QWidget *parent = nullptr); + explicit DynamicChartX(QWidget *parent = nullptr); ~DynamicChartX() override; protected: @@ -17,7 +16,9 @@ class DynamicChartX : public ChartView void dataReceived(int value); void startChart(); void setupChart(); - DynamicChartXPrivate *d; + + class DynamicChartXPrivate; + QScopedPointer d_ptr; }; #endif // DYNAMICCHARTX_H diff --git a/Chart/linechart.cpp b/Chart/linechart.cpp index e66574b..b863255 100644 --- a/Chart/linechart.cpp +++ b/Chart/linechart.cpp @@ -3,12 +3,14 @@ #include "callout.h" #include "dialogchart.h" -class LineChartPrivate{ +class LineChart::LineChartPrivate +{ public: - LineChartPrivate(ChartView *parent) - :owner(parent){ - lineSeries = new QLineSeries(owner); - scatterSeries = new QScatterSeries(owner); + explicit LineChartPrivate(ChartView *parent) + : q_ptr(parent) + { + lineSeries = new QLineSeries(q_ptr); + scatterSeries = new QScatterSeries(q_ptr); scatterSeries->setMarkerSize(8); chart = new QChart; @@ -29,11 +31,13 @@ class LineChartPrivate{ xValue->setText(QObject::tr("X: ")); yValue->setText(QObject::tr("Y: ")); - button = new QPushButton(QObject::tr("Eject"), owner); + button = new QPushButton(QObject::tr("Eject"), q_ptr); button->move(5, 5); button->setFlat(true); } - ChartView *owner; + + ChartView *q_ptr; + QChart *chart; QLineSeries *lineSeries; QScatterSeries *scatterSeries; @@ -48,33 +52,31 @@ class LineChartPrivate{ }; LineChart::LineChart(QWidget *parent) - :ChartView(parent) - ,d(new LineChartPrivate(this)) + : ChartView(parent) + , d_ptr(new LineChartPrivate(this)) { setupUI(); buildConnect(); } -LineChart::~LineChart() -{ - delete d; -} +LineChart::~LineChart() = default; void LineChart::resizeEvent(QResizeEvent *event) { //d->chart->resize(event->size()); - d->xValue->setPos(d->chart->size().width() - 170, 10); - d->yValue->setPos(d->chart->size().width() - 85, 10); - const auto callouts = d->toolTipList; - for (Callout *callout : callouts) + d_ptr->xValue->setPos(d_ptr->chart->size().width() - 170, 10); + d_ptr->yValue->setPos(d_ptr->chart->size().width() - 85, 10); + const auto callouts = d_ptr->toolTipList; + for (Callout *callout : callouts) { callout->updateGeometry(); + } QChartView::resizeEvent(event); } void LineChart::mouseMoveEvent(QMouseEvent *event) { - d->xValue->setText(QObject::tr("X: %1").arg(d->chart->mapToValue(event->pos()).x())); - d->yValue->setText(QObject::tr("Y: %1").arg(d->chart->mapToValue(event->pos()).x())); + d_ptr->xValue->setText(QObject::tr("X: %1").arg(d_ptr->chart->mapToValue(event->pos()).x())); + d_ptr->yValue->setText(QObject::tr("Y: %1").arg(d_ptr->chart->mapToValue(event->pos()).x())); QChartView::mouseMoveEvent(event); } @@ -82,42 +84,43 @@ void LineChart::wheelEvent(QWheelEvent *event) { int nd = event->angleDelta().rx() / 8; double scale =1.0 / pow(0.9, nd / 15.0f); - d->chart->zoom(scale); + d_ptr->chart->zoom(scale); update(); QChartView::wheelEvent(event); } void LineChart::keepToolTip() { - d->toolTipList.append(d->toolTip); - d->toolTip = new Callout(d->chart); + d_ptr->toolTipList.append(d_ptr->toolTip); + d_ptr->toolTip = new Callout(d_ptr->chart); } void LineChart::toolTip(QPointF point, bool state) { - if (d->toolTip == nullptr) - d->toolTip = new Callout(d->chart); + if (d_ptr->toolTip == nullptr) { + d_ptr->toolTip = new Callout(d_ptr->chart); + } if (state) { - d->toolTip->setText(QString(tr("X: %1 \nY: %2 ")).arg(point.x()).arg(point.y())); - d->toolTip->setAnchor(point); - d->toolTip->setZValue(11); - d->toolTip->updateGeometry(); - d->toolTip->show(); + d_ptr->toolTip->setText(QString(tr("X: %1 \nY: %2 ")).arg(point.x()).arg(point.y())); + d_ptr->toolTip->setAnchor(point); + d_ptr->toolTip->setZValue(11); + d_ptr->toolTip->updateGeometry(); + d_ptr->toolTip->show(); } else { - d->toolTip->hide(); + d_ptr->toolTip->hide(); } } void LineChart::showDialog() { hide(); - DialogChart *dialog = new DialogChart(d->chart->scene(), this); + DialogChart *dialog = new DialogChart(d_ptr->chart->scene(), this); dialog->resize(640, 480); dialog->exec(); delete dialog; dialog = nullptr; - setChart(d->chart); + setChart(d_ptr->chart); show(); } @@ -125,16 +128,16 @@ void LineChart::setupUI() { setMouseTracking(true); setRenderHint(QPainter::Antialiasing); - setChart(d->chart); + setChart(d_ptr->chart); PointList pointList = generateRandomDataPoints(5, 101); - d->lineSeries->replace(pointList); - d->scatterSeries->replace(pointList); + d_ptr->lineSeries->replace(pointList); + d_ptr->scatterSeries->replace(pointList); } void LineChart::buildConnect() { - connect(d->scatterSeries, &QScatterSeries::clicked, this, &LineChart::keepToolTip); - connect(d->scatterSeries, &QScatterSeries::hovered, this, &LineChart::toolTip); + connect(d_ptr->scatterSeries, &QScatterSeries::clicked, this, &LineChart::keepToolTip); + connect(d_ptr->scatterSeries, &QScatterSeries::hovered, this, &LineChart::toolTip); - connect(d->button, &QPushButton::clicked, this, &LineChart::showDialog); + connect(d_ptr->button, &QPushButton::clicked, this, &LineChart::showDialog); } diff --git a/Chart/linechart.h b/Chart/linechart.h index a01be21..db8ab15 100644 --- a/Chart/linechart.h +++ b/Chart/linechart.h @@ -3,12 +3,11 @@ #include "chartview.h" -class LineChartPrivate; class LineChart : public ChartView { Q_OBJECT public: - LineChart(QWidget *parent = nullptr); + explicit LineChart(QWidget *parent = nullptr); ~LineChart() override; protected: @@ -25,7 +24,9 @@ private slots: private: void setupUI(); void buildConnect(); - LineChartPrivate *d; + + class LineChartPrivate; + QScopedPointer d_ptr; }; #endif // LINECHART_H diff --git a/Chart/main.cpp b/Chart/main.cpp index fd3e533..24ba3b6 100644 --- a/Chart/main.cpp +++ b/Chart/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/Chart/mainwindow.cpp b/Chart/mainwindow.cpp index d14ef28..a92df2c 100644 --- a/Chart/mainwindow.cpp +++ b/Chart/mainwindow.cpp @@ -1,11 +1,11 @@ #include "mainwindow.h" +#include "areachart.h" +#include "datetimechart.h" #include "dynamicchart.h" #include "dynamicchartx.h" -#include "areachart.h" #include "linechart.h" -#include "stackedbarchart.h" #include "piechart.h" -#include "datetimechart.h" +#include "stackedbarchart.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) @@ -13,9 +13,7 @@ MainWindow::MainWindow(QWidget *parent) setupUI(); } -MainWindow::~MainWindow() -{ -} +MainWindow::~MainWindow() {} void MainWindow::setupUI() { @@ -33,4 +31,3 @@ void MainWindow::setupUI() setCentralWidget(frame); setMinimumSize(960, 600); } - diff --git a/Chart/mainwindow.h b/Chart/mainwindow.h index 249c63a..ad3198a 100644 --- a/Chart/mainwindow.h +++ b/Chart/mainwindow.h @@ -6,10 +6,9 @@ class MainWindow : public QMainWindow { Q_OBJECT - public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private: void setupUI(); diff --git a/Chart/normalchartdata.cpp b/Chart/normalchartdata.cpp index d7f9488..8be4713 100644 --- a/Chart/normalchartdata.cpp +++ b/Chart/normalchartdata.cpp @@ -1,10 +1,13 @@ #include "normalchartdata.h" -PointList generateRandomDataPoints(int listCount, int valueMax){ +#include + +auto generateRandomDataPoints(int listCount, int valueMax) -> PointList +{ PointList pointList; qreal yValue(0); int count = valueMax / listCount; - for(int i=0; ibounded(valueMax / qreal(listCount)); QPointF pointF(i, yValue); pointList.append(pointF); diff --git a/Chart/normalchartdata.h b/Chart/normalchartdata.h index f489ad2..e02e8f2 100644 --- a/Chart/normalchartdata.h +++ b/Chart/normalchartdata.h @@ -1,12 +1,11 @@ #ifndef NORMALCHARTDATA_H #define NORMALCHARTDATA_H -#include #include -#include +#include -typedef QList PointList; +using PointList = QList; -PointList generateRandomDataPoints(int listCount, int valueMax); +auto generateRandomDataPoints(int listCount, int valueMax) -> PointList; #endif // NORMALCHARTDATA_H diff --git a/Chart/piechart.cpp b/Chart/piechart.cpp index 4e1847f..68836c5 100644 --- a/Chart/piechart.cpp +++ b/Chart/piechart.cpp @@ -1,40 +1,41 @@ #include "piechart.h" #include "normalchartdata.h" -class PieChartPrivate{ +class PieChart::PieChartPrivate +{ public: - PieChartPrivate(ChartView *parent) - :owner(parent){ - pieSeries = new QPieSeries(owner); + explicit PieChartPrivate(ChartView *parent) + : q_ptr(parent) + { + pieSeries = new QPieSeries(q_ptr); chart = new QChart; chart->setAnimationOptions(QChart::AllAnimations); chart->setTitle(QObject::tr("Pie Chart")); } - ChartView *owner; + + ChartView *q_ptr; + QChart *chart; QPieSeries *pieSeries; }; PieChart::PieChart(QWidget *parent) - :ChartView(parent) - ,d(new PieChartPrivate(this)) + : ChartView(parent) + , d_ptr(new PieChartPrivate(this)) { setupUI(); } -PieChart::~PieChart() -{ - delete d; -} +PieChart::~PieChart() = default; void PieChart::setupUI() { setRenderHint(QPainter::Antialiasing); - setChart(d->chart); + setChart(d_ptr->chart); PointList pointList = generateRandomDataPoints(5, 100); for(int i=0; ipieSeries->append(tr("P%1").arg(i), pointList[i].y()); + QPieSlice *slice = d_ptr->pieSeries->append(tr("P%1").arg(i), pointList[i].y()); if(i == 0){ // Show the first slice exploded with label slice->setLabelVisible(); @@ -43,5 +44,5 @@ void PieChart::setupUI() } } - d->chart->addSeries(d->pieSeries); + d_ptr->chart->addSeries(d_ptr->pieSeries); } diff --git a/Chart/piechart.h b/Chart/piechart.h index 38d62b7..ba7e74a 100644 --- a/Chart/piechart.h +++ b/Chart/piechart.h @@ -3,16 +3,17 @@ #include "chartview.h" -class PieChartPrivate; class PieChart : public ChartView { public: - PieChart(QWidget *parent = nullptr); - ~PieChart(); + explicit PieChart(QWidget *parent = nullptr); + ~PieChart() override; private: void setupUI(); - PieChartPrivate *d; + + class PieChartPrivate; + QScopedPointer d_ptr; }; #endif // PIECHART_H diff --git a/Chart/stackedbarchart.cpp b/Chart/stackedbarchart.cpp index 7bdafd8..9f7bb2d 100644 --- a/Chart/stackedbarchart.cpp +++ b/Chart/stackedbarchart.cpp @@ -1,13 +1,15 @@ #include "stackedbarchart.h" #include "normalchartdata.h" -class StackedBarChartPrivate{ +class StackedBarChart::StackedBarChartPrivate +{ public: - StackedBarChartPrivate(ChartView *parent) - :owner(parent){ - stackedBarSeries = new QStackedBarSeries(owner); + explicit StackedBarChartPrivate(ChartView *parent) + : q_ptr(parent) + { + stackedBarSeries = new QStackedBarSeries(q_ptr); PointList pointList = generateRandomDataPoints(5, 101); - QBarSet *set = new QBarSet("Bar set", owner); + QBarSet *set = new QBarSet("Bar set", q_ptr); foreach(const QPointF& p, pointList) *set << p.y(); stackedBarSeries->append(set); // 先添加点集,不然x轴为空 @@ -20,24 +22,23 @@ class StackedBarChartPrivate{ chart->axes(Qt::Horizontal).first()->setRange(0, 100); chart->axes(Qt::Vertical).first()->setRange(0, 100); } - ChartView *owner; + + ChartView *q_ptr; + QChart *chart; QStackedBarSeries *stackedBarSeries; }; StackedBarChart::StackedBarChart(QWidget *parent) - :ChartView(parent) - ,d(new StackedBarChartPrivate(this)) + : ChartView(parent) + , d_ptr(new StackedBarChartPrivate(this)) { setupUI(); } -StackedBarChart::~StackedBarChart() -{ - delete d; -} +StackedBarChart::~StackedBarChart() = default; void StackedBarChart::setupUI() { - setChart(d->chart); + setChart(d_ptr->chart); } diff --git a/Chart/stackedbarchart.h b/Chart/stackedbarchart.h index ed01d07..56ef6cc 100644 --- a/Chart/stackedbarchart.h +++ b/Chart/stackedbarchart.h @@ -3,16 +3,17 @@ #include "chartview.h" -class StackedBarChartPrivate; class StackedBarChart : public ChartView { public: - StackedBarChart(QWidget *parent = nullptr); - ~StackedBarChart(); + explicit StackedBarChart(QWidget *parent = nullptr); + ~StackedBarChart() override; private: void setupUI(); - StackedBarChartPrivate *d; + + class StackedBarChartPrivate; + QScopedPointer d_ptr; }; #endif // STACKEDBARCHART_H diff --git a/CheckBoxStandardItem/main.cc b/CheckBoxStandardItem/main.cc index e9bbf59..5d48a9d 100644 --- a/CheckBoxStandardItem/main.cc +++ b/CheckBoxStandardItem/main.cc @@ -7,7 +7,7 @@ #include #endif -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/CheckBoxStandardItem/mainwindow.hpp b/CheckBoxStandardItem/mainwindow.hpp index 2a84cf2..2cabee1 100644 --- a/CheckBoxStandardItem/mainwindow.hpp +++ b/CheckBoxStandardItem/mainwindow.hpp @@ -1,19 +1,13 @@ #ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP -#include -#if QT_VERSION >= 0x050000 -#include -#else -#include -#endif +#include class MainWindow : public QMainWindow { Q_OBJECT - - public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); +public: + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_HPP diff --git a/Clock/clockwidget.cpp b/Clock/clockwidget.cpp index 466e72d..3b80fed 100644 --- a/Clock/clockwidget.cpp +++ b/Clock/clockwidget.cpp @@ -1,23 +1,27 @@ #include "clockwidget.h" +#include #include -#include -#include #include +#include #include -#include +#include -class ClockWidgetPrivate{ +class ClockWidget::ClockWidgetPrivate +{ public: - ClockWidgetPrivate(QWidget *parent) - : owner(parent){ + explicit ClockWidgetPrivate(QWidget *parent) + : q_ptr(parent) + { QTime time = QTime::currentTime(); hour = time.hour(); minute = time.minute(); second = time.minute(); microSecond = time.msec(); } - QWidget *owner; + + QWidget *q_ptr; + QColor borderColor = QColor(254, 254, 254); QColor backgroundColor = QColor(80, 80, 80); QColor foregroundColor = QColor(254, 254, 254); @@ -33,91 +37,89 @@ class ClockWidgetPrivate{ ClockWidget::ClockWidget(QWidget *parent) : QWidget(parent) - , d(new ClockWidgetPrivate(this)) + , d_ptr(new ClockWidgetPrivate(this)) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - connect(&d->timer, &QTimer::timeout, this, &ClockWidget::setOffset); - d->timer.start(1000); + connect(&d_ptr->timer, &QTimer::timeout, this, &ClockWidget::setOffset); + d_ptr->timer.start(1000); } -ClockWidget::~ClockWidget() -{ -} +ClockWidget::~ClockWidget() = default; void ClockWidget::setBorderColor(const QColor &color) { - d->borderColor = color; + d_ptr->borderColor = color; update(); } -QColor ClockWidget::borderColor() const +auto ClockWidget::borderColor() const -> QColor { - return d->borderColor; + return d_ptr->borderColor; } void ClockWidget::setBackgroundColor(const QColor &color) { - d->backgroundColor = color; + d_ptr->backgroundColor = color; update(); } -QColor ClockWidget::backgroundColor() const +auto ClockWidget::backgroundColor() const -> QColor { - return d->backgroundColor; + return d_ptr->backgroundColor; } void ClockWidget::setForegroundColor(const QColor &color) { - d->foregroundColor = color; + d_ptr->foregroundColor = color; update(); } -QColor ClockWidget::foregroundColor() const +auto ClockWidget::foregroundColor() const -> QColor { - return d->foregroundColor; + return d_ptr->foregroundColor; } void ClockWidget::setHourColor(const QColor &color) { - d->hourColor = color; + d_ptr->hourColor = color; update(); } -QColor ClockWidget::hourColor() const +auto ClockWidget::hourColor() const -> QColor { - return d->hourColor; + return d_ptr->hourColor; } void ClockWidget::setMinuteColor(const QColor &color) { - d->minuteColor = color; + d_ptr->minuteColor = color; update(); } -QColor ClockWidget::minuteColor() const +auto ClockWidget::minuteColor() const -> QColor { - return d->minuteColor; + return d_ptr->minuteColor; } void ClockWidget::setSecondColor(const QColor &color) { - d->secondColor = color; + d_ptr->secondColor = color; update(); } -QColor ClockWidget::secondColor() const +auto ClockWidget::secondColor() const -> QColor { - return d->secondColor; + return d_ptr->secondColor; } -QSize ClockWidget::sizeHint() const +auto ClockWidget::sizeHint() const -> QSize { - return QSize(500, 500); + return {500, 500}; } -QSize ClockWidget::minimumSizeHint() const +auto ClockWidget::minimumSizeHint() const -> QSize { - return QSize(300, 300); + return {300, 300}; } void ClockWidget::paintEvent(QPaintEvent *event) @@ -149,10 +151,10 @@ void ClockWidget::paintEvent(QPaintEvent *event) void ClockWidget::setOffset() { QTime time = QTime::currentTime(); - d->hour = time.hour(); - d->minute = time.minute(); - d->second = time.second(); - d->microSecond = time.msec(); + d_ptr->hour = time.hour(); + d_ptr->minute = time.minute(); + d_ptr->second = time.second(); + d_ptr->microSecond = time.msec(); update(); } @@ -161,7 +163,7 @@ void ClockWidget::drawBorder(QPainter *painter) double min = qMin(width(), height()); double radius = min / 2.0 - min / 10.0; painter->setPen(Qt::NoPen); - painter->setBrush(d->borderColor); + painter->setBrush(d_ptr->borderColor); painter->drawEllipse(-radius, -radius, radius * 2, radius * 2); } @@ -171,7 +173,7 @@ void ClockWidget::drawBackground(QPainter *painter) double radius = min / 2.0 - min / 9.0; painter->save(); painter->setPen(Qt::NoPen); - painter->setBrush(d->backgroundColor); + painter->setBrush(d_ptr->backgroundColor); painter->drawEllipse(-radius, -radius, radius * 2, radius * 2); painter->restore(); } @@ -181,7 +183,7 @@ void ClockWidget::drawScale(QPainter *painter, const double linew) painter->save(); double min = qMin(width(), height()); double radius = min / 2 - min / 8; - QPen pen(d->foregroundColor); + QPen pen(d_ptr->foregroundColor); pen.setCapStyle(Qt::RoundCap); for (int i = 0; i <= 60; i++) { @@ -203,7 +205,7 @@ void ClockWidget::drawScaleNum(QPainter *painter) { double min = qMin(width(), height()); double radius = min / 2.0 - min / 4.8; - painter->setPen(d->foregroundColor); + painter->setPen(d_ptr->foregroundColor); QFont font("Microsoft YaHei", min / 20); painter->setFont(font); @@ -229,14 +231,13 @@ void ClockWidget::drawHour(QPainter *painter) painter->save(); QPen pen; pen.setCapStyle(Qt::RoundCap); - painter->setPen(d->hourColor); - painter->setBrush(d->hourColor); + painter->setPen(d_ptr->hourColor); + painter->setBrush(d_ptr->hourColor); double min = qMin(width(), height()) / 6.0; QPolygonF pts; - pts << QPointF(-3, 8) << QPointF(3, 8) - << QPointF(2, -min) << QPointF(-2, -min); - painter->rotate(30.0 * ((d->hour + d->minute / 60.0))); + pts << QPointF(-3, 8) << QPointF(3, 8) << QPointF(2, -min) << QPointF(-2, -min); + painter->rotate(30.0 * ((d_ptr->hour + d_ptr->minute / 60.0))); painter->drawConvexPolygon(pts); painter->restore(); } @@ -246,14 +247,13 @@ void ClockWidget::drawMinute(QPainter *painter) painter->save(); QPen pen; pen.setCapStyle(Qt::RoundCap); - painter->setPen(d->minuteColor); - painter->setBrush(d->minuteColor); + painter->setPen(d_ptr->minuteColor); + painter->setBrush(d_ptr->minuteColor); double min = qMin(width(), height()) / 5.0; QPolygonF pts; - pts << QPointF(-2, 8) << QPointF(2, 8) - << QPointF(1, -min) << QPointF(-1, -min); - painter->rotate(6.0 * (d->minute + d->second / 60.0)); + pts << QPointF(-2, 8) << QPointF(2, 8) << QPointF(1, -min) << QPointF(-1, -min); + painter->rotate(6.0 * (d_ptr->minute + d_ptr->second / 60.0)); painter->drawConvexPolygon(pts); painter->restore(); } @@ -263,13 +263,13 @@ void ClockWidget::drawSecond(QPainter *painter) painter->save(); QPen pen; pen.setCapStyle(Qt::RoundCap); - painter->setPen(d->secondColor); - painter->setBrush(d->secondColor); + painter->setPen(d_ptr->secondColor); + painter->setBrush(d_ptr->secondColor); double min = qMin(width(), height()) / 4.0; QPolygonF pts; pts << QPointF(-1, 10) << QPointF(1, 10) << QPointF(0, -min); - painter->rotate(6.0 * (d->second + d->microSecond / 1000.0)); + painter->rotate(6.0 * (d_ptr->second + d_ptr->microSecond / 1000.0)); painter->drawConvexPolygon(pts); painter->restore(); } @@ -278,14 +278,12 @@ void ClockWidget::drawDot(QPainter *painter) { painter->save(); QConicalGradient coneGradient(0, 0, -90.0); - coneGradient.setColorAt(0.0, d->backgroundColor); - coneGradient.setColorAt(0.5, d->foregroundColor); - coneGradient.setColorAt(1.0, d->backgroundColor); + coneGradient.setColorAt(0.0, d_ptr->backgroundColor); + coneGradient.setColorAt(0.5, d_ptr->foregroundColor); + coneGradient.setColorAt(1.0, d_ptr->backgroundColor); painter->setOpacity(0.9); painter->setPen(Qt::NoPen); painter->setBrush(coneGradient); painter->drawEllipse(-5, -5, 10, 10); painter->restore(); } - - diff --git a/Clock/clockwidget.h b/Clock/clockwidget.h index b2c57f4..9cf3235 100644 --- a/Clock/clockwidget.h +++ b/Clock/clockwidget.h @@ -3,7 +3,6 @@ #include -class ClockWidgetPrivate; class ClockWidget : public QWidget { Q_OBJECT @@ -15,28 +14,28 @@ class ClockWidget : public QWidget Q_PROPERTY(QColor secondColor READ secondColor WRITE setSecondColor) public: explicit ClockWidget(QWidget *parent = nullptr); - ~ClockWidget(); + ~ClockWidget() override; - QSize sizeHint() const override; - QSize minimumSizeHint() const override; + [[nodiscard]] auto sizeHint() const -> QSize override; + [[nodiscard]] auto minimumSizeHint() const -> QSize override; void setBorderColor(const QColor &color); - QColor borderColor() const; + [[nodiscard]] auto borderColor() const -> QColor; void setBackgroundColor(const QColor &color); - QColor backgroundColor() const; + [[nodiscard]] auto backgroundColor() const -> QColor; void setForegroundColor(const QColor &color); - QColor foregroundColor() const; + [[nodiscard]] auto foregroundColor() const -> QColor; void setHourColor(const QColor &color); - QColor hourColor() const; + [[nodiscard]] auto hourColor() const -> QColor; void setMinuteColor(const QColor &color); - QColor minuteColor() const; + [[nodiscard]] auto minuteColor() const -> QColor; void setSecondColor(const QColor &color); - QColor secondColor() const; + [[nodiscard]] auto secondColor() const -> QColor; protected: void paintEvent(QPaintEvent *event) override; @@ -47,14 +46,15 @@ private slots: private: void drawBorder(QPainter *painter); void drawBackground(QPainter *painter); - void drawScale(QPainter *painter, const double linew); + void drawScale(QPainter *painter, double linew); void drawScaleNum(QPainter *painter); void drawHour(QPainter *painter); void drawMinute(QPainter *painter); void drawSecond(QPainter *painter); void drawDot(QPainter *painter); - QScopedPointer d; + class ClockWidgetPrivate; + QScopedPointer d_ptr; }; #endif // CLOCKWIDGET_H diff --git a/Clock/main.cpp b/Clock/main.cpp index fd3e533..24ba3b6 100644 --- a/Clock/main.cpp +++ b/Clock/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/Clock/mainwindow.cpp b/Clock/mainwindow.cpp index 097f162..ae20f1c 100644 --- a/Clock/mainwindow.cpp +++ b/Clock/mainwindow.cpp @@ -9,7 +9,4 @@ MainWindow::MainWindow(QWidget *parent) resize(600, 480); } -MainWindow::~MainWindow() -{ -} - +MainWindow::~MainWindow() = default; diff --git a/Clock/mainwindow.h b/Clock/mainwindow.h index d147190..b50d227 100644 --- a/Clock/mainwindow.h +++ b/Clock/mainwindow.h @@ -8,7 +8,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_H diff --git a/DashBoard/dashboardwidget.cpp b/DashBoard/dashboardwidget.cpp index 35235d8..245febf 100644 --- a/DashBoard/dashboardwidget.cpp +++ b/DashBoard/dashboardwidget.cpp @@ -4,7 +4,8 @@ #include #include -struct DashBoardWidgetPrivate{ +struct DashBoardWidget::DashBoardWidgetPrivate +{ double maxValue = 100; double minValue = 0; double startAngle = -50; @@ -26,168 +27,166 @@ struct DashBoardWidgetPrivate{ DashBoardWidget::DashBoardWidget(QWidget *parent) : QWidget(parent) - , d(new DashBoardWidgetPrivate) + , d_ptr(new DashBoardWidgetPrivate) { - d->animation = new QPropertyAnimation(this, "value", this); + d_ptr->animation = new QPropertyAnimation(this, "value", this); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); connect(this, &DashBoardWidget::valueChanged, this, &DashBoardWidget::onStartAnimation); } -DashBoardWidget::~DashBoardWidget() -{ -} +DashBoardWidget::~DashBoardWidget() = default; -QSize DashBoardWidget::sizeHint() const +auto DashBoardWidget::sizeHint() const -> QSize { - return QSize(300, 300); + return {300, 300}; } -QSize DashBoardWidget::minimumSizeHint() const +auto DashBoardWidget::minimumSizeHint() const -> QSize { - return QSize(200, 200); + return {200, 200}; } void DashBoardWidget::setMin(const double min) { - d->minValue = min; + d_ptr->minValue = min; update(); } -double DashBoardWidget::min() const +auto DashBoardWidget::min() const -> double { - return d->minValue; + return d_ptr->minValue; } void DashBoardWidget::setmax(const double max) { - d->maxValue = max; + d_ptr->maxValue = max; update(); } -double DashBoardWidget::max() const +auto DashBoardWidget::max() const -> double { - return d->maxValue; + return d_ptr->maxValue; } void DashBoardWidget::setStartAngle(const double startAngle) { - d->startAngle = startAngle; + d_ptr->startAngle = startAngle; update(); } -double DashBoardWidget::startAngle() const +auto DashBoardWidget::startAngle() const -> double { - return d->startAngle; + return d_ptr->startAngle; } void DashBoardWidget::setEndAngle(const double endAngle) { - d->endAngle = endAngle; + d_ptr->endAngle = endAngle; update(); } -double DashBoardWidget::endAngle() const +auto DashBoardWidget::endAngle() const -> double { - return d->endAngle; + return d_ptr->endAngle; } void DashBoardWidget::setScaleMajor(const int scale) { - d->scaleMajor = scale; + d_ptr->scaleMajor = scale; update(); } -int DashBoardWidget::scaleMajor() const +auto DashBoardWidget::scaleMajor() const -> int { - return d->scaleMajor; + return d_ptr->scaleMajor; } void DashBoardWidget::setScaleMinor(const int scale) { - d->scaleMinor = scale; + d_ptr->scaleMinor = scale; update(); } -int DashBoardWidget::scaleMinor() const +auto DashBoardWidget::scaleMinor() const -> int { - return d->scaleMinor; + return d_ptr->scaleMinor; } void DashBoardWidget::setUnit(const QString &unit) { - d->unit = unit; + d_ptr->unit = unit; update(); } -QString DashBoardWidget::unit() const +auto DashBoardWidget::unit() const -> QString { - return d->unit; + return d_ptr->unit; } void DashBoardWidget::setText(const QString &text) { - d->text = text; + d_ptr->text = text; update(); } -QString DashBoardWidget::text() const +auto DashBoardWidget::text() const -> QString { - return d->text; + return d_ptr->text; } void DashBoardWidget::setArcColor(const QColor &color) { - d->arcColor = color; + d_ptr->arcColor = color; update(); } -QColor DashBoardWidget::arcColor() const +auto DashBoardWidget::arcColor() const -> QColor { - return d->arcColor; + return d_ptr->arcColor; } void DashBoardWidget::setScaleColor(const QColor &color) { - d->scaleColor = color; + d_ptr->scaleColor = color; update(); } -QColor DashBoardWidget::scaleColor() const +auto DashBoardWidget::scaleColor() const -> QColor { - return d->scaleColor; + return d_ptr->scaleColor; } void DashBoardWidget::setPointerColor(const QColor &color) { - d->pointerColor = color; + d_ptr->pointerColor = color; update(); } -QColor DashBoardWidget::pointerColor() const +auto DashBoardWidget::pointerColor() const -> QColor { - return d->pointerColor; + return d_ptr->pointerColor; } void DashBoardWidget::setTextColor(const QColor &color) { - d->textColor = color; + d_ptr->textColor = color; update(); } -QColor DashBoardWidget::textColor() const +auto DashBoardWidget::textColor() const -> QColor { - return d->textColor; + return d_ptr->textColor; } void DashBoardWidget::setBackgroundColor(const QColor &color) { - d->backgroundColor = color; + d_ptr->backgroundColor = color; update(); } -QColor DashBoardWidget::backgroundColor() const +auto DashBoardWidget::backgroundColor() const -> QColor { - return d->backgroundColor; + return d_ptr->backgroundColor; } void DashBoardWidget::paintEvent(QPaintEvent *event) @@ -197,9 +196,9 @@ void DashBoardWidget::paintEvent(QPaintEvent *event) painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); // 背景 - if (d->backgroundColor != Qt::transparent) { + if (d_ptr->backgroundColor != Qt::transparent) { painter.setPen(Qt::NoPen); - painter.fillRect(rect(), d->backgroundColor); + painter.fillRect(rect(), d_ptr->backgroundColor); } // 平移中心 @@ -223,27 +222,26 @@ void DashBoardWidget::paintEvent(QPaintEvent *event) void DashBoardWidget::onStartAnimation(const double value) { - if(value < d->minValue - || value > d->maxValue - || value == d->value) + if (value < d_ptr->minValue || value > d_ptr->maxValue || value == d_ptr->value) { return; - - int start = d->value; +} + + int start = d_ptr->value; int end = value; - - d->animation->setStartValue(start); - d->animation->setEndValue(end); - d->animation->start(); + + d_ptr->animation->setStartValue(start); + d_ptr->animation->setEndValue(end); + d_ptr->animation->start(); } -double DashBoardWidget::value() const +auto DashBoardWidget::value() const -> double { - return d->value; + return d_ptr->value; } void DashBoardWidget::setValue(const double value) { - d->value = value; + d_ptr->value = value; update(); } @@ -258,27 +256,27 @@ void DashBoardWidget::drawArc(QPainter *painter) pen.setCapStyle(Qt::FlatCap); // 圆弧背景 - double angle = d->endAngle - d->startAngle; - pen.setColor(d->arcColor); + double angle = d_ptr->endAngle - d_ptr->startAngle; + pen.setColor(d_ptr->arcColor); painter->setPen(pen); - painter->drawArc(rect, d->startAngle * 16, angle * 16); + painter->drawArc(rect, d_ptr->startAngle * 16, angle * 16); } void DashBoardWidget::drawScale(QPainter *painter) { painter->save(); - - painter->rotate(270 - d->endAngle); - int steps = (d->scaleMajor * d->scaleMinor); - double angleStep = (d->endAngle - d->startAngle) / steps; + + painter->rotate(270 - d_ptr->endAngle); + int steps = (d_ptr->scaleMajor * d_ptr->scaleMinor); + double angleStep = (d_ptr->endAngle - d_ptr->startAngle) / steps; double min = qMin(width(), height()); double radius = min / 3; - - QPen pen(d->scaleColor); + + QPen pen(d_ptr->scaleColor); pen.setCapStyle(Qt::RoundCap); for (int i = 0; i <= steps; i++) { - if (i % d->scaleMinor == 0) { + if (i % d_ptr->scaleMinor == 0) { pen.setWidthF(1.5); painter->setPen(pen); painter->drawLine(0, radius - 8, 0, radius + 5); @@ -297,20 +295,20 @@ void DashBoardWidget::drawScale(QPainter *painter) void DashBoardWidget::drawScaleNum(QPainter *painter) { painter->save(); - painter->setPen(d->scaleColor); + painter->setPen(d_ptr->scaleColor); double min = qMin(width(), height()); double radius = min / 2.4; QFont font("Microsoft YaHei", min / 25); painter->setFont(font); - - double startRad = d->endAngle * (M_PI / 180); - double deltaRad = (d->endAngle - d->startAngle) * (M_PI / 180) / d->scaleMajor; + + double startRad = d_ptr->endAngle * (M_PI / 180); + double deltaRad = (d_ptr->endAngle - d_ptr->startAngle) * (M_PI / 180) / d_ptr->scaleMajor; QFontMetrics fontMetrics(font); - for (int i = 0; i <= d->scaleMajor; i++) { + for (int i = 0; i <= d_ptr->scaleMajor; i++) { double sina = qSin(startRad - i * deltaRad); double cosa = qCos(startRad - i * deltaRad); - double value = 1.0 * i * ((d->maxValue - d->minValue) / d->scaleMajor) + d->minValue; + double value = 1.0 * i * ((d_ptr->maxValue - d_ptr->minValue) / d_ptr->scaleMajor) + d_ptr->minValue; QString strValue = QString("%1").arg(value, 0, 'f', 2); double textWidth = fontMetrics.horizontalAdvance(strValue); @@ -327,16 +325,16 @@ void DashBoardWidget::drawPointer(QPainter *painter) { painter->save(); painter->setPen(Qt::NoPen); - painter->setBrush(d->pointerColor); + painter->setBrush(d_ptr->pointerColor); double radius = qMin(width(), height()) / 3.0; QPolygonF pts; - pts << QPointF(-5, 0) << QPointF(0, -8) - << QPointF(5, 0) << QPointF(0, radius); - - painter->rotate(270 - d->endAngle); - double degRotate = (d->endAngle - d->startAngle) / (d->maxValue - d->minValue) * (d->value - d->minValue); + pts << QPointF(-5, 0) << QPointF(0, -8) << QPointF(5, 0) << QPointF(0, radius); + + painter->rotate(270 - d_ptr->endAngle); + double degRotate = (d_ptr->endAngle - d_ptr->startAngle) / (d_ptr->maxValue - d_ptr->minValue) + * (d_ptr->value - d_ptr->minValue); painter->rotate(degRotate); painter->drawConvexPolygon(pts); @@ -346,22 +344,22 @@ void DashBoardWidget::drawPointer(QPainter *painter) void DashBoardWidget::drawValue(QPainter *painter) { painter->save(); - painter->setPen(d->textColor); + painter->setPen(d_ptr->textColor); double min = qMin(width(), height()); double radius = min / 2.0 - min / 4.8; QFont font("Microsoft YaHei", min / 25); painter->setFont(font); - - QString strValue = QString("%1").arg(d->value, 0, 'f', 2); - strValue = QString("%1 %2").arg(strValue, d->unit); + + QString strValue = QString("%1").arg(d_ptr->value, 0, 'f', 2); + strValue = QString("%1 %2").arg(strValue, d_ptr->unit); QRectF valueRect(-radius, radius / 2.5, radius * 2, radius / 3.5); painter->drawText(valueRect, Qt::AlignCenter, strValue); QRectF textRect(-radius, radius / 1.5, radius * 2, radius / 2.5); //font.setPixelSize(12); painter->setFont(font); - painter->drawText(textRect, Qt::AlignCenter, d->text); + painter->drawText(textRect, Qt::AlignCenter, d_ptr->text); painter->restore(); } diff --git a/DashBoard/dashboardwidget.h b/DashBoard/dashboardwidget.h index dd44e2c..0e9aeb4 100644 --- a/DashBoard/dashboardwidget.h +++ b/DashBoard/dashboardwidget.h @@ -3,7 +3,6 @@ #include -struct DashBoardWidgetPrivate; class DashBoardWidget : public QWidget { Q_OBJECT @@ -23,52 +22,52 @@ class DashBoardWidget : public QWidget Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor) public: explicit DashBoardWidget(QWidget *parent = nullptr); - ~DashBoardWidget(); + ~DashBoardWidget() override; - QSize sizeHint() const override; - QSize minimumSizeHint() const override; + [[nodiscard]] auto sizeHint() const -> QSize override; + [[nodiscard]] auto minimumSizeHint() const -> QSize override; - double value() const; + [[nodiscard]] auto value() const -> double; void setValue(const double value); void setMin(const double min); - double min() const; + [[nodiscard]] auto min() const -> double; void setmax(const double max); - double max() const; + [[nodiscard]] auto max() const -> double; void setStartAngle(const double startAngle); - double startAngle() const; + [[nodiscard]] auto startAngle() const -> double; void setEndAngle(const double endAngle); - double endAngle() const; + [[nodiscard]] auto endAngle() const -> double; void setScaleMajor(const int scale); - int scaleMajor() const; + [[nodiscard]] auto scaleMajor() const -> int; void setScaleMinor(const int scale); - int scaleMinor() const; + [[nodiscard]] auto scaleMinor() const -> int; void setUnit(const QString &unit); - QString unit() const; + [[nodiscard]] auto unit() const -> QString; void setText(const QString &text); - QString text() const; + [[nodiscard]] auto text() const -> QString; void setArcColor(const QColor &color); - QColor arcColor() const; + [[nodiscard]] auto arcColor() const -> QColor; void setScaleColor(const QColor &color); - QColor scaleColor() const; + [[nodiscard]] auto scaleColor() const -> QColor; void setPointerColor(const QColor &color); - QColor pointerColor() const; + [[nodiscard]] auto pointerColor() const -> QColor; void setTextColor(const QColor &color); - QColor textColor() const; + [[nodiscard]] auto textColor() const -> QColor; void setBackgroundColor(const QColor &color); - QColor backgroundColor() const; + [[nodiscard]] auto backgroundColor() const -> QColor; signals: void valueChanged(const double value); @@ -86,7 +85,8 @@ private slots: void drawPointer(QPainter *painter); void drawValue(QPainter *painter); - QScopedPointer d; + struct DashBoardWidgetPrivate; + QScopedPointer d_ptr; }; #endif // DASHBOARDWIDGET_H diff --git a/DashBoard/main.cpp b/DashBoard/main.cpp index fd3e533..24ba3b6 100644 --- a/DashBoard/main.cpp +++ b/DashBoard/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/DashBoard/mainwindow.h b/DashBoard/mainwindow.h index d147190..b50d227 100644 --- a/DashBoard/mainwindow.h +++ b/DashBoard/mainwindow.h @@ -8,7 +8,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_H diff --git a/DragDrop/draglistwidget.cpp b/DragDrop/draglistwidget.cpp index db72eba..e748fc1 100644 --- a/DragDrop/draglistwidget.cpp +++ b/DragDrop/draglistwidget.cpp @@ -1,11 +1,9 @@ #include "draglistwidget.h" DragListWidget::DragListWidget(QWidget *parent) - :QListWidget(parent) + : QListWidget(parent) { setDragEnabled(true); - QStringList list; - list << tr("Hello") << tr("World") << tr("Good") << - tr("Study") << tr("Day") << tr("Up"); + QStringList list{tr("Hello"), tr("World"), tr("Good"), tr("Study"), tr("Day"), tr("Up")}; addItems(list); } diff --git a/DragDrop/draglistwidget.h b/DragDrop/draglistwidget.h index db135e9..9493a99 100644 --- a/DragDrop/draglistwidget.h +++ b/DragDrop/draglistwidget.h @@ -7,7 +7,7 @@ class DragListWidget : public QListWidget { Q_OBJECT public: - DragListWidget(QWidget *parent = nullptr); + explicit DragListWidget(QWidget *parent = nullptr); }; #endif // DRAGLISTWIDGET_H diff --git a/DragDrop/droplistwidget.cpp b/DragDrop/droplistwidget.cpp index 29edd50..5d4a520 100644 --- a/DragDrop/droplistwidget.cpp +++ b/DragDrop/droplistwidget.cpp @@ -3,7 +3,7 @@ #include DropListWidget::DropListWidget(QWidget *parent) - :QListWidget(parent) + : QListWidget(parent) { setDragEnabled(true); setAcceptDrops(true); @@ -13,14 +13,15 @@ DropListWidget::DropListWidget(QWidget *parent) void DropListWidget::setupUI() { - menu = new QMenu(this); - menu->addAction(tr("delete"), this, [this]{ + m_menu = new QMenu(this); + m_menu->addAction(tr("delete"), this, [this] { removeItemWidget(currentItem()); delete currentItem(); }); - connect(this, &DropListWidget::customContextMenuRequested, this, [this]{ - if (!currentItem()) + connect(this, &DropListWidget::customContextMenuRequested, this, [this] { + if (!currentItem()) { return; - menu->exec(QCursor::pos()); + } + m_menu->exec(QCursor::pos()); }); } diff --git a/DragDrop/droplistwidget.h b/DragDrop/droplistwidget.h index 97770bb..73d0e6e 100644 --- a/DragDrop/droplistwidget.h +++ b/DragDrop/droplistwidget.h @@ -7,11 +7,12 @@ class DropListWidget : public QListWidget { Q_OBJECT public: - DropListWidget(QWidget *parent = nullptr); + explicit DropListWidget(QWidget *parent = nullptr); private: void setupUI(); - QMenu *menu; + + QMenu *m_menu; }; #endif // DROPLISTWIDGET_H diff --git a/DragDrop/main.cpp b/DragDrop/main.cpp index fd3e533..24ba3b6 100644 --- a/DragDrop/main.cpp +++ b/DragDrop/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/DragDrop/mainwindow.h b/DragDrop/mainwindow.h index 3a3484e..e8b9e0b 100644 --- a/DragDrop/mainwindow.h +++ b/DragDrop/mainwindow.h @@ -11,7 +11,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); + explicit MainWindow(QWidget *parent = nullptr); protected: void dragEnterEvent(QDragEnterEvent *event) override; diff --git a/FlowLayout/flowlayout.cpp b/FlowLayout/flowlayout.cpp index 9a48855..35e35e2 100644 --- a/FlowLayout/flowlayout.cpp +++ b/FlowLayout/flowlayout.cpp @@ -53,13 +53,16 @@ #include "flowlayout.h" //! [1] FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing) - : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) + : QLayout(parent) + , m_hSpace(hSpacing) + , m_vSpace(vSpacing) { setContentsMargins(margin, margin, margin, margin); } FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) - : m_hSpace(hSpacing), m_vSpace(vSpacing) + : m_hSpace(hSpacing) + , m_vSpace(vSpacing) { setContentsMargins(margin, margin, margin, margin); } @@ -69,8 +72,9 @@ FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) FlowLayout::~FlowLayout() { QLayoutItem *item; - while ((item = takeAt(0))) + while ((item = takeAt(0))) { delete item; + } } //! [2] @@ -82,7 +86,7 @@ void FlowLayout::addItem(QLayoutItem *item) //! [3] //! [4] -int FlowLayout::horizontalSpacing() const +auto FlowLayout::horizontalSpacing() const -> int { if (m_hSpace >= 0) { return m_hSpace; @@ -91,7 +95,7 @@ int FlowLayout::horizontalSpacing() const } } -int FlowLayout::verticalSpacing() const +auto FlowLayout::verticalSpacing() const -> int { if (m_vSpace >= 0) { return m_vSpace; @@ -102,20 +106,21 @@ int FlowLayout::verticalSpacing() const //! [4] //! [5] -int FlowLayout::count() const +auto FlowLayout::count() const -> int { return itemList.size(); } -QLayoutItem *FlowLayout::itemAt(int index) const +auto FlowLayout::itemAt(int index) const -> QLayoutItem * { return itemList.value(index); } -QLayoutItem *FlowLayout::takeAt(int index) +auto FlowLayout::takeAt(int index) -> QLayoutItem * { - if (index >= 0 && index < itemList.size()) + if (index >= 0 && index < itemList.size()) { return itemList.takeAt(index); + } return nullptr; } //! [5] @@ -123,17 +128,17 @@ QLayoutItem *FlowLayout::takeAt(int index) //! [6] Qt::Orientations FlowLayout::expandingDirections() const { - return { }; + return {}; } //! [6] //! [7] -bool FlowLayout::hasHeightForWidth() const +auto FlowLayout::hasHeightForWidth() const -> bool { return true; } -int FlowLayout::heightForWidth(int width) const +auto FlowLayout::heightForWidth(int width) const -> int { int height = doLayout(QRect(0, 0, width, 0), true); return height; @@ -147,12 +152,12 @@ void FlowLayout::setGeometry(const QRect &rect) doLayout(rect, false); } -QSize FlowLayout::sizeHint() const +auto FlowLayout::sizeHint() const -> QSize { return minimumSize(); } -QSize FlowLayout::minimumSize() const +auto FlowLayout::minimumSize() const -> QSize { QSize size; for (const QLayoutItem *item : qAsConst(itemList)) @@ -165,7 +170,7 @@ QSize FlowLayout::minimumSize() const //! [8] //! [9] -int FlowLayout::doLayout(const QRect &rect, bool testOnly) const +auto FlowLayout::doLayout(const QRect &rect, bool testOnly) const -> int { int left, top, right, bottom; getContentsMargins(&left, &top, &right, &bottom); @@ -173,21 +178,23 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const int x = effectiveRect.x(); int y = effectiveRect.y(); int lineHeight = 0; -//! [9] + //! [9] -//! [10] + //! [10] for (QLayoutItem *item : qAsConst(itemList)) { const QWidget *wid = item->widget(); int spaceX = horizontalSpacing(); if (spaceX == -1) - spaceX = wid->style()->layoutSpacing( - QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); + spaceX = wid->style()->layoutSpacing(QSizePolicy::PushButton, + QSizePolicy::PushButton, + Qt::Horizontal); int spaceY = verticalSpacing(); if (spaceY == -1) - spaceY = wid->style()->layoutSpacing( - QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical); -//! [10] -//! [11] + spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, + QSizePolicy::PushButton, + Qt::Vertical); + //! [10] + //! [11] int nextX = x + item->sizeHint().width() + spaceX; if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { x = effectiveRect.x(); @@ -206,7 +213,7 @@ int FlowLayout::doLayout(const QRect &rect, bool testOnly) const } //! [11] //! [12] -int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const +auto FlowLayout::smartSpacing(QStyle::PixelMetric pm) const -> int { QObject *parent = this->parent(); if (!parent) { diff --git a/FlowLayout/flowlayout.h b/FlowLayout/flowlayout.h index 3155d5d..727d1ae 100644 --- a/FlowLayout/flowlayout.h +++ b/FlowLayout/flowlayout.h @@ -60,24 +60,24 @@ class FlowLayout : public QLayout public: explicit FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); - ~FlowLayout(); + ~FlowLayout() override; void addItem(QLayoutItem *item) override; - int horizontalSpacing() const; - int verticalSpacing() const; - Qt::Orientations expandingDirections() const override; - bool hasHeightForWidth() const override; - int heightForWidth(int) const override; - int count() const override; - QLayoutItem *itemAt(int index) const override; - QSize minimumSize() const override; + [[nodiscard]] auto horizontalSpacing() const -> int; + [[nodiscard]] auto verticalSpacing() const -> int; + [[nodiscard]] Qt::Orientations expandingDirections() const override; + [[nodiscard]] auto hasHeightForWidth() const -> bool override; + [[nodiscard]] auto heightForWidth(int) const -> int override; + [[nodiscard]] auto count() const -> int override; + [[nodiscard]] auto itemAt(int index) const -> QLayoutItem * override; + [[nodiscard]] auto minimumSize() const -> QSize override; void setGeometry(const QRect &rect) override; - QSize sizeHint() const override; - QLayoutItem *takeAt(int index) override; + [[nodiscard]] auto sizeHint() const -> QSize override; + auto takeAt(int index) -> QLayoutItem * override; private: - int doLayout(const QRect &rect, bool testOnly) const; - int smartSpacing(QStyle::PixelMetric pm) const; + [[nodiscard]] auto doLayout(const QRect &rect, bool testOnly) const -> int; + [[nodiscard]] auto smartSpacing(QStyle::PixelMetric pm) const -> int; QList itemList; int m_hSpace; diff --git a/FlowLayout/flowwidget.cc b/FlowLayout/flowwidget.cc index fbf4b1e..bb4ced1 100644 --- a/FlowLayout/flowwidget.cc +++ b/FlowLayout/flowwidget.cc @@ -34,12 +34,12 @@ class FlowWidget::FlowWidgetPrivate { public: FlowWidgetPrivate(QWidget *parent) - : owner(parent) + : q_ptr(parent) { - flowLayout = new FlowLayout(owner, 9, 5, 5); + flowLayout = new FlowLayout(q_ptr, 9, 5, 5); } - QWidget *owner; + QWidget *q_ptr; FlowLayout *flowLayout; }; diff --git a/FlowLayout/flowwidget.hpp b/FlowLayout/flowwidget.hpp index 2aa4300..4973141 100644 --- a/FlowLayout/flowwidget.hpp +++ b/FlowLayout/flowwidget.hpp @@ -16,7 +16,7 @@ class LabelWidget : public QWidget public: explicit LabelWidget(const QString &text, QWidget *parent); - QString text() const; + [[nodiscard]] auto text() const -> QString; signals: void removed(); @@ -30,12 +30,12 @@ class FlowWidget : public QWidget Q_OBJECT public: explicit FlowWidget(QWidget *parent = nullptr); - ~FlowWidget(); + ~FlowWidget() override; void setItems(const QStringList &list); void addItem(const QString &text); - QStringList items() const; + [[nodiscard]] auto items() const -> QStringList; private slots: void onRemoved(); diff --git a/FlowLayout/main.cc b/FlowLayout/main.cc index e9bbf59..5d48a9d 100644 --- a/FlowLayout/main.cc +++ b/FlowLayout/main.cc @@ -7,7 +7,7 @@ #include #endif -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/FlowLayout/mainwindow.hpp b/FlowLayout/mainwindow.hpp index 2a84cf2..ebd3d81 100644 --- a/FlowLayout/mainwindow.hpp +++ b/FlowLayout/mainwindow.hpp @@ -1,19 +1,14 @@ #ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP -#include -#if QT_VERSION >= 0x050000 -#include -#else -#include -#endif +#include class MainWindow : public QMainWindow { Q_OBJECT - public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); +public: + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_HPP diff --git a/GridViewModel/gridmodel.cpp b/GridViewModel/gridmodel.cpp index e172c7b..2a40b36 100644 --- a/GridViewModel/gridmodel.cpp +++ b/GridViewModel/gridmodel.cpp @@ -2,24 +2,22 @@ #include -GridModel::GridModel(QObject* parent) +GridModel::GridModel(QObject *parent) : QAbstractListModel(parent) -{ - -} +{} -QVariant GridModel::data(const QModelIndex &index, int role) const +auto GridModel::data(const QModelIndex &index, int role) const -> QVariant { ImageInfo *image = m_imageVector.at(index.row()); - switch(role){ + switch (role) { case Qt::DecorationRole: return image->image; //case Qt::DisplayRole: return image->filename; - case Qt::ToolTipRole:return image->color; + case Qt::ToolTipRole: return image->color; case Qt::SizeHintRole: return QSize(WIDTH, WIDTH); case Qt::TextAlignmentRole: return Qt::AlignCenter; default: break; } - return QVariant(); + return {}; } diff --git a/GridViewModel/gridmodel.h b/GridViewModel/gridmodel.h index 1f5785f..7138a52 100644 --- a/GridViewModel/gridmodel.h +++ b/GridViewModel/gridmodel.h @@ -6,27 +6,32 @@ #define WIDTH 80 -struct ImageInfo{ +struct ImageInfo +{ QImage image; QString color; }; -typedef QVector ImageVector; +using ImageVector = QVector; class GridModel : public QAbstractListModel { public: - GridModel(QObject* parent = nullptr); - int rowCount(const QModelIndex & = QModelIndex()) const override - { return m_imageVector.size(); } - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + explicit GridModel(QObject *parent = nullptr); + [[nodiscard]] auto rowCount(const QModelIndex & = QModelIndex()) const -> int override + { + return m_imageVector.size(); + } + [[nodiscard]] auto data(const QModelIndex &index, int role = Qt::DisplayRole) const + -> QVariant override; - void setImageVector(const ImageVector& imageVector) + void setImageVector(const ImageVector &imageVector) { beginResetModel(); m_imageVector = imageVector; endResetModel(); } + private: ImageVector m_imageVector; }; diff --git a/GridViewModel/gridview.cpp b/GridViewModel/gridview.cpp index 82f4290..37c0ce2 100644 --- a/GridViewModel/gridview.cpp +++ b/GridViewModel/gridview.cpp @@ -12,8 +12,9 @@ GridView::GridView(QWidget *parent) void GridView::onSelectChanged() { QItemSelectionModel *selModel = selectionModel(); - if(!selModel) + if (!selModel) { return; + } qDebug() << selModel->selectedIndexes(); } @@ -32,5 +33,8 @@ void GridView::setupUI() void GridView::buildConnect() { - connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, &GridView::onSelectChanged); + connect(selectionModel(), + &QItemSelectionModel::selectionChanged, + this, + &GridView::onSelectChanged); } diff --git a/GridViewModel/gridview.h b/GridViewModel/gridview.h index 77315de..a9bcb5e 100644 --- a/GridViewModel/gridview.h +++ b/GridViewModel/gridview.h @@ -8,10 +8,12 @@ class GridView : public QListView { public: - GridView(QWidget* parent = nullptr); + explicit GridView(QWidget *parent = nullptr); - void setImageVector(const ImageVector& imageVector) - { m_gridModel->setImageVector(imageVector); } + void setImageVector(const ImageVector &imageVector) + { + m_gridModel->setImageVector(imageVector); + } private slots: void onSelectChanged(); diff --git a/GridViewModel/main.cpp b/GridViewModel/main.cpp index fd3e533..24ba3b6 100644 --- a/GridViewModel/main.cpp +++ b/GridViewModel/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/GridViewModel/mainwindow.h b/GridViewModel/mainwindow.h index dad3811..4e0ea3b 100644 --- a/GridViewModel/mainwindow.h +++ b/GridViewModel/mainwindow.h @@ -10,8 +10,8 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private: void setupUI(); diff --git a/HttpClient/httpclient.cpp b/HttpClient/httpclient.cpp index 50b58c4..59ddd33 100644 --- a/HttpClient/httpclient.cpp +++ b/HttpClient/httpclient.cpp @@ -10,15 +10,17 @@ enum Method { GET, POST, PUT, DELETE }; -class HttpClientPrivate +class HttpClient::HttpClientPrivate { public: - HttpClientPrivate(QObject *parent) - : owner(parent) + explicit HttpClientPrivate(QObject *parent) + : q_ptr(parent) { - manager = new QNetworkAccessManager(owner); + manager = new QNetworkAccessManager(q_ptr); } - QObject *owner; + + QObject *q_ptr; + QNetworkAccessManager *manager; HttpClient::HttpHeaders headers; QString url; @@ -31,56 +33,58 @@ class HttpClientPrivate HttpClient::HttpClient(QObject *parent) : QObject(parent) - , d(new HttpClientPrivate(this)) + , d_ptr(new HttpClientPrivate(this)) {} -HttpClient::~HttpClient() {} +HttpClient::~HttpClient() = default; void HttpClient::setHeaders(const HttpClient::HttpHeaders &headers) { - d->headers = headers; + d_ptr->headers = headers; } void HttpClient::setJson(const QString &json) { - d->json = json; + d_ptr->json = json; } void HttpClient::setParams(const HttpClient::HttpParams ¶ms) { - for (HttpParams::const_iterator iter = params.begin(); iter != params.end(); iter++) - d->params.addQueryItem(iter.key(), iter.value().toString()); + for (HttpParams::const_iterator iter = params.begin(); iter != params.end(); iter++) { + d_ptr->params.addQueryItem(iter.key(), iter.value().toString()); + } } void HttpClient::get(const QString &url) { - d->method = GET; + d_ptr->method = GET; startRequest(url); } void HttpClient::post(const QString &url) { - d->method = POST; + d_ptr->method = POST; startRequest(url); } void HttpClient::put(const QString &url) { - d->method = PUT; + d_ptr->method = PUT; startRequest(url); } void HttpClient::remove(const QString &url) { - d->method = DELETE; + d_ptr->method = DELETE; startRequest(url); } void HttpClient::download(const QString &url, const QString &savePath) { - if (url.isEmpty() || !QUrl(url).isValid()) + if (url.isEmpty() || !QUrl(url).isValid()) { return; - d->url = url; + } + d_ptr->url = url; if (QFileInfo::exists(savePath)) { qWarning() << tr("[Error] File already exists: %1.").arg(savePath); @@ -94,18 +98,21 @@ void HttpClient::download(const QString &url, const QString &savePath) return; } QNetworkRequest request = createRequest(); - QNetworkReply *reply = d->manager->get(request); - if (!reply) + QNetworkReply *reply = d_ptr->manager->get(request); + if (!reply) { return; + } connect(reply, &QNetworkReply::readyRead, this, [=] { - if (reply->bytesAvailable() > 0) + if (reply->bytesAvailable() > 0) { file->write(reply->readAll()); + } }); connect(reply, &QNetworkReply::finished, this, [=] { - if (reply->bytesAvailable() > 0) + if (reply->bytesAvailable() > 0) { file->write(reply->readAll()); + } delete file; reply->deleteLater(); emit finish(); @@ -123,8 +130,9 @@ void HttpClient::upload(const QString &url, const QString &path) void HttpClient::upload(const QString &url, const QStringList &paths) { - if (paths.isEmpty()) + if (paths.isEmpty()) { return; + } QHttpMultiPart *multiPart = initMultiPart(url); QString inputName = paths.size() == 1 ? "file" @@ -158,8 +166,9 @@ void HttpClient::upload(const QString &url, const QStringList &paths) void HttpClient::upload(const QString &url, const QByteArray &data) { - if (data.isEmpty()) + if (data.isEmpty()) { return; + } QHttpMultiPart *multiPart = initMultiPart(url); @@ -176,11 +185,13 @@ void HttpClient::slotReadyRead() { qDebug() << "slotReadyRead"; QNetworkReply *reply = qobject_cast(sender()); - if (!reply) + if (!reply) { return; + } - if (reply->bytesAvailable() <= 0) + if (reply->bytesAvailable() <= 0) { return; + } QByteArray buf = reply->readAll(); qDebug() << buf.size(); @@ -191,11 +202,13 @@ void HttpClient::slotReplyFinish() { qDebug() << "slotReplyFinish"; QNetworkReply *reply = qobject_cast(sender()); - if (!reply) + if (!reply) { return; + } - if (reply->bytesAvailable() > 0) + if (reply->bytesAvailable() > 0) { emit readyReady(reply->readAll()); + } reply->deleteLater(); reply = nullptr; @@ -206,11 +219,13 @@ void HttpClient::slotReplyFinish() void HttpClient::slotError(QNetworkReply::NetworkError replyError) { QNetworkReply *reply = qobject_cast(sender()); - if (!reply) + if (!reply) { return; + } - if (replyError == QNetworkReply::NoError) + if (replyError == QNetworkReply::NoError) { return; + } emit error(reply->errorString()); } @@ -218,19 +233,21 @@ void HttpClient::slotError(QNetworkReply::NetworkError replyError) void HttpClient::slotSslErrors(const QList &errors) { QNetworkReply *reply = qobject_cast(sender()); - if (!reply) + if (!reply) { return; + } qDebug() << errors; } -QHttpMultiPart *HttpClient::initMultiPart(const QString &url) +auto HttpClient::initMultiPart(const QString &url) -> QHttpMultiPart * { - if (url.isEmpty() || !QUrl(url).isValid()) + if (url.isEmpty() || !QUrl(url).isValid()) { return nullptr; - d->url = url; + } + d_ptr->url = url; QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this); - QList> paramItems = d->params.queryItems(); + QList> paramItems = d_ptr->params.queryItems(); for (int i = 0; i < paramItems.size(); ++i) { QString name = paramItems.at(i).first; QString value = paramItems.at(i).second; @@ -248,9 +265,10 @@ QHttpMultiPart *HttpClient::initMultiPart(const QString &url) void HttpClient::execUpload(QHttpMultiPart *multiPart) { QNetworkRequest request = createRequest(); - QNetworkReply *reply = d->manager->post(request, multiPart); - if (!reply) + QNetworkReply *reply = d_ptr->manager->post(request, multiPart); + if (!reply) { return; + } multiPart->setParent(reply); // delete the multiPart with the reply connect(reply, &QNetworkReply::finished, this, [this, reply] { reply->deleteLater(); @@ -263,9 +281,10 @@ void HttpClient::execUpload(QHttpMultiPart *multiPart) void HttpClient::startRequest(const QString &url) { - if (url.isEmpty() || !QUrl(url).isValid()) + if (url.isEmpty() || !QUrl(url).isValid()) { return; - d->url = url; + } + d_ptr->url = url; execRequest(); } @@ -274,39 +293,41 @@ void HttpClient::execRequest() QNetworkRequest request = createRequest(); QNetworkReply *reply = nullptr; - switch (d->method) { - case GET: reply = d->manager->get(request); break; + switch (d_ptr->method) { + case GET: reply = d_ptr->manager->get(request); break; case POST: - reply = d->manager->post(request, - d->useJson ? d->json.toUtf8() - : d->params.toString(QUrl::FullyEncoded).toUtf8()); + reply = d_ptr->manager->post(request, + d_ptr->useJson + ? d_ptr->json.toUtf8() + : d_ptr->params.toString(QUrl::FullyEncoded).toUtf8()); break; case PUT: - reply = d->manager->put(request, - d->useJson ? d->json.toUtf8() - : d->params.toString(QUrl::FullyEncoded).toUtf8()); + reply = d_ptr->manager->put(request, + d_ptr->useJson + ? d_ptr->json.toUtf8() + : d_ptr->params.toString(QUrl::FullyEncoded).toUtf8()); break; - case DELETE: reply = d->manager->deleteResource(request); break; + case DELETE: reply = d_ptr->manager->deleteResource(request); break; default: return; } buildConnect(reply); } -QNetworkRequest HttpClient::createRequest() +auto HttpClient::createRequest() -> QNetworkRequest { - bool get = d->method == GET; - bool withForm = !get && !d->useJson; // PUT、POST 或者 DELETE 请求,且 useJson 为 false - bool withJson = !get && d->useJson; // PUT、POST 或者 DELETE 请求,且 useJson 为 true + bool get = d_ptr->method == GET; + bool withForm = !get && !d_ptr->useJson; // PUT、POST 或者 DELETE 请求,且 useJson 为 false + bool withJson = !get && d_ptr->useJson; // PUT、POST 或者 DELETE 请求,且 useJson 为 true - if (get && !d->params.isEmpty()) { - d->url += "?" + d->params.toString(QUrl::FullyEncoded); + if (get && !d_ptr->params.isEmpty()) { + d_ptr->url += "?" + d_ptr->params.toString(QUrl::FullyEncoded); } - qDebug() << tr("URL: ") << d->url; + qDebug() << tr("URL: ") << d_ptr->url; if (withForm) { - QList> paramItems = d->params.queryItems(); + QList> paramItems = d_ptr->params.queryItems(); QString buffer; // 避免多次调用 qDebug() 输入调试信息,每次 qDebug() 都有可能输出行号等 // 按键值对的方式输出参数 @@ -314,27 +335,29 @@ QNetworkRequest HttpClient::createRequest() QString name = paramItems.at(i).first; QString value = paramItems.at(i).second; - if (0 == i) + if (0 == i) { buffer += QString("params: %1=%2\n").arg(name, value); - else + } else { buffer += QString(" %1=%2\n").arg(name, value); + } } - if (!buffer.isEmpty()) + if (!buffer.isEmpty()) { qDebug() << buffer; + } } // [3] 设置 Content-Type // 如果是 POST 请求,useJson 为 true 时添加 Json 的请求头,useJson 为 false 时添加 Form 的请求头 if (withForm) { - d->headers["Content-Type"] = "application/x-www-form-urlencoded"; + d_ptr->headers["Content-Type"] = "application/x-www-form-urlencoded"; } else if (withJson) { - d->headers["Content-Type"] = "application/json; charset=utf-8"; + d_ptr->headers["Content-Type"] = "application/json; charset=utf-8"; } // [4] 添加请求头到 request 中 - QNetworkRequest request(QUrl(d->url)); - for (auto i = d->headers.cbegin(); i != d->headers.cend(); ++i) { + QNetworkRequest request(QUrl(d_ptr->url)); + for (auto i = d_ptr->headers.cbegin(); i != d_ptr->headers.cend(); ++i) { request.setRawHeader(i.key().toUtf8(), i.value().toUtf8()); } diff --git a/HttpClient/httpclient.h b/HttpClient/httpclient.h index ddfbc51..cddf547 100644 --- a/HttpClient/httpclient.h +++ b/HttpClient/httpclient.h @@ -4,16 +4,15 @@ #include #include -class HttpClientPrivate; class HttpClient : public QObject { Q_OBJECT public: - typedef QHash HttpHeaders; - typedef QMap HttpParams; + using HttpHeaders = QHash; + using HttpParams = QMap; explicit HttpClient(QObject *parent = nullptr); - ~HttpClient(); + ~HttpClient() override; public slots: void setHeaders(const HttpClient::HttpHeaders&); @@ -47,14 +46,15 @@ private slots: void slotSslErrors(const QList &errors); private: - QHttpMultiPart *initMultiPart(const QString &url); + auto initMultiPart(const QString &url) -> QHttpMultiPart *; void execUpload(QHttpMultiPart*); void startRequest(const QString &url); void execRequest(); - QNetworkRequest createRequest(); + auto createRequest() -> QNetworkRequest; void buildConnect(QNetworkReply *reply); - QScopedPointer d; + class HttpClientPrivate; + QScopedPointer d_ptr; }; #endif // HTTPCLIENT_H diff --git a/HttpClient/httpclientthread.cpp b/HttpClient/httpclientthread.cpp index e94d605..40dc2ad 100644 --- a/HttpClient/httpclientthread.cpp +++ b/HttpClient/httpclientthread.cpp @@ -8,7 +8,7 @@ HttpClientThread::HttpClientThread(QObject *parent) HttpClientThread::~HttpClientThread() { - if(isRunning()){ + if (isRunning()) { quit(); wait(); } @@ -27,17 +27,21 @@ void HttpClientThread::run() connect(this, &HttpClientThread::remove, httpClient.data(), &HttpClient::remove); connect(this, &HttpClientThread::download, httpClient.data(), &HttpClient::download); -// connect(this, SIGNAL(upload(const QString &url, const QString &path)), -// httpClient.data(), SLOT(upload(const QString &url, const QString &path))); -// connect(this, SIGNAL(upload(const QString &url, const QStringList &paths)), -// httpClient.data(), SLOT(upload(const QString &url, const QStringList &paths))); -// connect(this, SIGNAL(upload(const QString &url, const QByteArray &data)), -// httpClient.data(), SLOT(upload(const QString &url, const QByteArray &data))); + // connect(this, SIGNAL(upload(const QString &url, const QString &path)), + // httpClient.data(), SLOT(upload(const QString &url, const QString &path))); + // connect(this, SIGNAL(upload(const QString &url, const QStringList &paths)), + // httpClient.data(), SLOT(upload(const QString &url, const QStringList &paths))); + // connect(this, SIGNAL(upload(const QString &url, const QByteArray &data)), + // httpClient.data(), SLOT(upload(const QString &url, const QByteArray &data))); connect(httpClient.data(), &HttpClient::error, this, &HttpClientThread::error); connect(httpClient.data(), &HttpClient::readyReady, this, &HttpClientThread::readyReady); - connect(httpClient.data(), &HttpClient::downloadProgress, this, &HttpClientThread::downloadProgress); + connect(httpClient.data(), + &HttpClient::downloadProgress, + this, + &HttpClientThread::downloadProgress); connect(httpClient.data(), &HttpClient::uploadProgress, this, &HttpClientThread::uploadProgress); connect(httpClient.data(), &HttpClient::finish, this, &HttpClientThread::finish); + exec(); } diff --git a/HttpClient/httpclientthread.h b/HttpClient/httpclientthread.h index 766ed6e..7bf579e 100644 --- a/HttpClient/httpclientthread.h +++ b/HttpClient/httpclientthread.h @@ -9,13 +9,13 @@ class HttpClientThread : public QThread { Q_OBJECT public: - HttpClientThread(QObject *parent = nullptr); - ~HttpClientThread(); + explicit HttpClientThread(QObject *parent = nullptr); + ~HttpClientThread() override; signals: - void setHeaders(const HttpClient::HttpHeaders&); - void setJson(const QString& json); - void setParams(const HttpClient::HttpParams& params); + void setHeaders(const HttpClient::HttpHeaders &); + void setJson(const QString &json); + void setParams(const HttpClient::HttpParams ¶ms); void get(const QString &url); void post(const QString &url); @@ -31,8 +31,8 @@ class HttpClientThread : public QThread void upload(const QString &url, const QByteArray &data); //------------------------------------------------------------- - void error(const QString&); - void readyReady(const QByteArray&); + void error(const QString &); + void readyReady(const QByteArray &); void downloadProgress(qint64 bytesSent, qint64 bytesTotal); void uploadProgress(qint64 bytesSent, qint64 bytesTotal); void finish(); diff --git a/HttpClient/main.cpp b/HttpClient/main.cpp index fd3e533..24ba3b6 100644 --- a/HttpClient/main.cpp +++ b/HttpClient/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/HttpClient/mainwindow.cpp b/HttpClient/mainwindow.cpp index 7df48b4..2f987fd 100644 --- a/HttpClient/mainwindow.cpp +++ b/HttpClient/mainwindow.cpp @@ -2,13 +2,15 @@ #include "httpclient.h" //#include "httpclientthread.h" -#include #include +#include -class MainWindowPrivate{ +class MainWindowPrivate +{ public: - MainWindowPrivate(QWidget *parent) - : owner(parent){ + explicit MainWindowPrivate(QWidget *parent) + : owner(parent) + { urlEdit = new QLineEdit(owner); urlEdit->setText("http://www.baidu.com"); urlEdit->setPlaceholderText(QObject::tr("http://url")); @@ -37,14 +39,12 @@ MainWindow::MainWindow(QWidget *parent) buildConnect(); } -MainWindow::~MainWindow() -{ -} +MainWindow::~MainWindow() {} void MainWindow::onRequest() { QString url = d->urlEdit->text(); - if(url.isEmpty() || !QUrl(url).isValid()) + if (url.isEmpty() || !QUrl(url).isValid()) return; d->requestButton->setEnabled(false); d->elapsedTimer.start(); @@ -66,18 +66,18 @@ void MainWindow::onAppendBytes(const QByteArray &bytes) void MainWindow::onAppendText() { - if(d->bytes.isEmpty()) + if (d->bytes.isEmpty()) return; - if(d->bytes.size() > 2000){ + if (d->bytes.size() > 2000) { d->textEdit->append(d->bytes.left(2000)); d->bytes.remove(0, 2000); - }else{ + } else { d->textEdit->append(d->bytes); d->bytes.clear(); } - if(d->bytes.isEmpty() && !d->requestButton->isChecked()) + if (d->bytes.isEmpty() && !d->requestButton->isChecked()) d->timer.stop(); } @@ -108,4 +108,3 @@ void MainWindow::buildConnect() // connect(d->httpClientThread, &HttpClientThread::error, d->textEdit, &QPlainTextEdit::appendPlainText); // connect(d->httpClientThread, &HttpClientThread::finish, this, &MainWindow::onFinish); } - diff --git a/HttpClient/mainwindow.h b/HttpClient/mainwindow.h index 9a0e114..a13d067 100644 --- a/HttpClient/mainwindow.h +++ b/HttpClient/mainwindow.h @@ -9,8 +9,8 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private slots: void onRequest(); diff --git a/LogAsynchronous/fileutil.cpp b/LogAsynchronous/fileutil.cpp index c575ac9..78aff9c 100644 --- a/LogAsynchronous/fileutil.cpp +++ b/LogAsynchronous/fileutil.cpp @@ -12,11 +12,12 @@ const static int kRollPerSeconds_ = 60 * 60 * 24; -bool generateDirectorys(const QString &directory) +auto generateDirectorys(const QString &directory) -> bool { QDir sourceDir(directory); - if (sourceDir.exists()) + if (sourceDir.exists()) { return true; +} QString tempDir; QStringList directorys = directory.split("/"); @@ -25,8 +26,9 @@ bool generateDirectorys(const QString &directory) tempDir += path + "/"; QDir dir(tempDir); - if (!dir.exists() && !dir.mkdir(tempDir)) + if (!dir.exists() && !dir.mkdir(tempDir)) { return false; +} } return true; @@ -79,7 +81,7 @@ void FileUtil::onFlush() d_ptr->stream.flush(); } -QString FileUtil::getFileName(qint64 *now) const +auto FileUtil::getFileName(qint64 *now) const -> QString { *now = QDateTime::currentSecsSinceEpoch(); QString data = QDateTime::fromSecsSinceEpoch(*now).toString("yyyy-MM-dd-hh-mm-ss"); @@ -92,7 +94,7 @@ QString FileUtil::getFileName(qint64 *now) const return filename; } -bool FileUtil::rollFile(int count) +auto FileUtil::rollFile(int count) -> bool { qint64 now = 0; QString filename = getFileName(&now); diff --git a/LogAsynchronous/fileutil.h b/LogAsynchronous/fileutil.h index cf07159..88aa5be 100644 --- a/LogAsynchronous/fileutil.h +++ b/LogAsynchronous/fileutil.h @@ -9,7 +9,7 @@ class FileUtil : public QObject Q_OBJECT public: explicit FileUtil(qint64 days = 30, QObject *parent = nullptr); - ~FileUtil(); + ~FileUtil() override; public slots: void onWrite(const QString &); @@ -18,8 +18,8 @@ private slots: void onFlush(); private: - QString getFileName(qint64 *now) const; - bool rollFile(int); + auto getFileName(qint64 *now) const -> QString; + auto rollFile(int) -> bool; void autoDelFile(); void setTimer(); diff --git a/LogAsynchronous/logasync.cpp b/LogAsynchronous/logasync.cpp index 2538f3b..fb98d2b 100644 --- a/LogAsynchronous/logasync.cpp +++ b/LogAsynchronous/logasync.cpp @@ -7,8 +7,9 @@ // 消息处理函数 void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { - if (type < LogAsync::instance()->logLevel()) + if (type < LogAsync::instance()->logLevel()) { return; +} FILE *stdPrint = stdout; QString level; @@ -78,7 +79,7 @@ struct LogAsyncPrivate QMutex LogAsync::m_mutex; -LogAsync *LogAsync::instance() +auto LogAsync::instance() -> LogAsync * { QMutexLocker locker(&m_mutex); static LogAsync log; @@ -90,7 +91,7 @@ void LogAsync::setOrientation(LogAsync::Orientation orientation) d_ptr->orientation = orientation; } -LogAsync::Orientation LogAsync::orientation() +auto LogAsync::orientation() -> LogAsync::Orientation { return d_ptr->orientation; } @@ -100,7 +101,7 @@ void LogAsync::setLogLevel(QtMsgType type) d_ptr->msgType = type; } -QtMsgType LogAsync::logLevel() +auto LogAsync::logLevel() -> QtMsgType { return d_ptr->msgType; } diff --git a/LogAsynchronous/logasync.h b/LogAsynchronous/logasync.h index 6429309..df0a1c2 100644 --- a/LogAsynchronous/logasync.h +++ b/LogAsynchronous/logasync.h @@ -11,13 +11,13 @@ class LogAsync : public QThread public: enum Orientation { Std = 1, File, StdAndFile }; - static LogAsync *instance(); + static auto instance() -> LogAsync *; void setOrientation(Orientation); - Orientation orientation(); + auto orientation() -> Orientation; void setLogLevel(QtMsgType); - QtMsgType logLevel(); + auto logLevel() -> QtMsgType; void startWork(); void stop(); @@ -29,7 +29,7 @@ class LogAsync : public QThread void run() override; private: - LogAsync(QObject *parent = nullptr); + explicit LogAsync(QObject *parent = nullptr); ~LogAsync() override; static QMutex m_mutex; diff --git a/LogAsynchronous/main.cpp b/LogAsynchronous/main.cpp index 0bddd25..4e79682 100644 --- a/LogAsynchronous/main.cpp +++ b/LogAsynchronous/main.cpp @@ -5,7 +5,7 @@ #include "logasync.h" #include "mainwindow.h" -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); diff --git a/LogAsynchronous/mainwindow.h b/LogAsynchronous/mainwindow.h index 6485032..a073161 100644 --- a/LogAsynchronous/mainwindow.h +++ b/LogAsynchronous/mainwindow.h @@ -8,8 +8,8 @@ class MainWindow : public QMainWindow { Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private: void testLog(); diff --git a/MulClient/main.cpp b/MulClient/main.cpp index fd3e533..24ba3b6 100644 --- a/MulClient/main.cpp +++ b/MulClient/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/MulClient/mainwindow.cpp b/MulClient/mainwindow.cpp index 2811546..9a81d44 100644 --- a/MulClient/mainwindow.cpp +++ b/MulClient/mainwindow.cpp @@ -6,7 +6,7 @@ class MainWindowPrivate { public: - MainWindowPrivate(QWidget *owner) + explicit MainWindowPrivate(QWidget *owner) : owner(owner) { ipEdit = new QLineEdit(owner); diff --git a/MulClient/mainwindow.h b/MulClient/mainwindow.h index b4337fb..582318e 100644 --- a/MulClient/mainwindow.h +++ b/MulClient/mainwindow.h @@ -8,13 +8,13 @@ class MainWindow : public QMainWindow { Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private slots: void onConnect(bool); void onWrite(); - void removeOne(const int index); + void removeOne(int index); private: void warningBox(const QString&, QWidget*); diff --git a/MulClient/tcpclient.cpp b/MulClient/tcpclient.cpp index c47bc9e..669f1dc 100644 --- a/MulClient/tcpclient.cpp +++ b/MulClient/tcpclient.cpp @@ -13,7 +13,7 @@ TcpClient::~TcpClient() qDebug() << "~TcpClient"; } -QString TcpClient::getInfo() const +auto TcpClient::getInfo() const -> QString { QString info = peerName() + " " + peerAddress().toString() + " " + QString::number(peerPort()) + " "; diff --git a/MulClient/tcpclient.h b/MulClient/tcpclient.h index 7fc0488..acfb9ef 100644 --- a/MulClient/tcpclient.h +++ b/MulClient/tcpclient.h @@ -7,13 +7,13 @@ class TcpClient : public QTcpSocket { Q_OBJECT public: - TcpClient(QObject *parent = nullptr); - ~TcpClient(); + explicit TcpClient(QObject *parent = nullptr); + ~TcpClient() override; - QString getInfo() const; + [[nodiscard]] auto getInfo() const -> QString; public slots: - void onWrite(const QByteArray&); + void onWrite(const QByteArray &); void onReadyRead(); }; diff --git a/MulClient/tcpclientthread.cpp b/MulClient/tcpclientthread.cpp index 204ce0d..90eb23e 100644 --- a/MulClient/tcpclientthread.cpp +++ b/MulClient/tcpclientthread.cpp @@ -3,7 +3,7 @@ class TcpClientThreadPrivate{ public: - TcpClientThreadPrivate(QThread *parent = nullptr) + explicit TcpClientThreadPrivate(QThread *parent = nullptr) : owner(parent){} QThread *owner; QString ip = "127.0.0.1"; diff --git a/MulClient/tcpclientthread.h b/MulClient/tcpclientthread.h index 6606b4f..5948198 100644 --- a/MulClient/tcpclientthread.h +++ b/MulClient/tcpclientthread.h @@ -9,14 +9,14 @@ class TcpClientThread : public QThread Q_OBJECT public: TcpClientThread(const QString &ip, - const quint16 port, - const int index, + quint16 port, + int index, QObject *parent = nullptr); ~TcpClientThread() override; signals: void writeToServer(const QByteArray&); - void quitThread(const int); + void quitThread(int); private slots: void removeMyself(); diff --git a/MulServer/accepter.h b/MulServer/accepter.h index f893850..950e17c 100644 --- a/MulServer/accepter.h +++ b/MulServer/accepter.h @@ -7,7 +7,7 @@ class Accepter : public QThread { Q_OBJECT public: - Accepter(quint16, QObject *parent = nullptr); + explicit Accepter(quint16, QObject *parent = nullptr); ~Accepter() override; signals: diff --git a/MulServer/main.cpp b/MulServer/main.cpp index fd3e533..24ba3b6 100644 --- a/MulServer/main.cpp +++ b/MulServer/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/MulServer/mainwindow.cpp b/MulServer/mainwindow.cpp index a9a4bcb..451f373 100644 --- a/MulServer/mainwindow.cpp +++ b/MulServer/mainwindow.cpp @@ -7,7 +7,7 @@ class MainWindowPrivate { public: - MainWindowPrivate(QMainWindow* owner) : owner(owner){ + explicit MainWindowPrivate(QMainWindow* owner) : owner(owner){ ipBox = new QComboBox(owner); portEdit = new QLineEdit(owner); listenBtn = new QPushButton(QObject::tr("Listen"), owner); diff --git a/MulServer/mainwindow.h b/MulServer/mainwindow.h index d526548..84f9a8c 100644 --- a/MulServer/mainwindow.h +++ b/MulServer/mainwindow.h @@ -9,8 +9,8 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private slots: void onListen(bool); diff --git a/MulServer/tcpclient.cpp b/MulServer/tcpclient.cpp index d8bb39d..e99a100 100644 --- a/MulServer/tcpclient.cpp +++ b/MulServer/tcpclient.cpp @@ -12,7 +12,7 @@ TcpClient::~TcpClient() qDebug() << "~TcpSocket"; } -QString TcpClient::getInfo() const +auto TcpClient::getInfo() const -> QString { QString info = peerName() + " " + peerAddress().toString() + " " + QString::number(peerPort()) + " "; diff --git a/MulServer/tcpclient.h b/MulServer/tcpclient.h index 1fe3fcb..f41c2de 100644 --- a/MulServer/tcpclient.h +++ b/MulServer/tcpclient.h @@ -7,10 +7,10 @@ class TcpClient : public QTcpSocket { Q_OBJECT public: - TcpClient(QObject *parent = nullptr); - ~TcpClient(); + explicit TcpClient(QObject *parent = nullptr); + ~TcpClient() override; - QString getInfo() const; + [[nodiscard]] auto getInfo() const -> QString; public slots: void onReadyRead(); diff --git a/MulServer/tcpserver.h b/MulServer/tcpserver.h index e4a66cc..638119c 100644 --- a/MulServer/tcpserver.h +++ b/MulServer/tcpserver.h @@ -7,7 +7,7 @@ class TcpServer : public QTcpServer { Q_OBJECT public: - TcpServer(QObject *parent = nullptr); + explicit TcpServer(QObject *parent = nullptr); ~TcpServer() override; signals: diff --git a/MulServer/thread.h b/MulServer/thread.h index e05b247..3bb330b 100644 --- a/MulServer/thread.h +++ b/MulServer/thread.h @@ -8,7 +8,7 @@ class Thread : public QThread { Q_OBJECT public: - Thread(qintptr socketDescriptor, QObject *parent = nullptr); + explicit Thread(qintptr socketDescriptor, QObject *parent = nullptr); ~Thread() override; signals: diff --git a/NavigationProgressBar/main.cpp b/NavigationProgressBar/main.cpp index fd3e533..24ba3b6 100644 --- a/NavigationProgressBar/main.cpp +++ b/NavigationProgressBar/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/NavigationProgressBar/mainwindow.h b/NavigationProgressBar/mainwindow.h index d147190..b50d227 100644 --- a/NavigationProgressBar/mainwindow.h +++ b/NavigationProgressBar/mainwindow.h @@ -8,7 +8,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_H diff --git a/NavigationProgressBar/navigationprogressbar.cpp b/NavigationProgressBar/navigationprogressbar.cpp index fc1aa76..621403f 100644 --- a/NavigationProgressBar/navigationprogressbar.cpp +++ b/NavigationProgressBar/navigationprogressbar.cpp @@ -1,15 +1,17 @@ #include "navigationprogressbar.h" -#include #include #include +#include -class NavigationProgressBarPrivate{ +class NavigationProgressBarPrivate +{ public: - NavigationProgressBarPrivate(QWidget *parent) - : owner(parent){ - for(int i=0; i QSize { - return QSize(500, 100); + return {500, 100}; } -QSize NavigationProgressBar::minimumSizeHint() const +auto NavigationProgressBar::minimumSizeHint() const -> QSize { - return QSize(300, 75); + return {300, 75}; } void NavigationProgressBar::setMessageList(const QStringList &list) @@ -48,25 +47,26 @@ void NavigationProgressBar::setMessageList(const QStringList &list) update(); } -QStringList NavigationProgressBar::messageList() const +auto NavigationProgressBar::messageList() const -> QStringList { return d->topInfo; } void NavigationProgressBar::setStep(const int step) { - if(d->step >= step || step > d->maxStep) + if (d->step >= step || step > d->maxStep) { return; +} int s = step - d->step; - for(int i=0; idateList.append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")); d->step = step; Q_ASSERT(d->step == d->dateList.size()); update(); } -int NavigationProgressBar::step() const +auto NavigationProgressBar::step() const -> int { return d->step; } @@ -77,7 +77,7 @@ void NavigationProgressBar::setBackgroundColor(const QColor &color) update(); } -QColor NavigationProgressBar::backgroundColor() const +auto NavigationProgressBar::backgroundColor() const -> QColor { return d->backgroundColor; } @@ -88,7 +88,7 @@ void NavigationProgressBar::setCurrentBackgroundColor(const QColor &color) update(); } -QColor NavigationProgressBar::currentBackgroundColor() const +auto NavigationProgressBar::currentBackgroundColor() const -> QColor { return d->currentBackgroundColor; } @@ -99,7 +99,7 @@ void NavigationProgressBar::setForegroundColor(const QColor &color) update(); } -QColor NavigationProgressBar::foregroundColor() const +auto NavigationProgressBar::foregroundColor() const -> QColor { return d->foregroundColor; } @@ -131,7 +131,7 @@ void NavigationProgressBar::drawBackground(QPainter *painter, const bool ok) int step = d->maxStep; int penWidth = radius / 4; QColor backgroundColor = d->backgroundColor; - if(ok){ + if (ok) { step = d->step; penWidth = radius / 8; backgroundColor = d->currentBackgroundColor; @@ -149,8 +149,9 @@ void NavigationProgressBar::drawBackground(QPainter *painter, const bool ok) initX += w; } - if(ok && (d->step > 0) && (d->step < d->maxStep)) + if (ok && (d->step > 0) && (d->step < d->maxStep)) { painter->drawLine(QPoint(initX, initY), QPoint(initX + w / 2, initY)); +} //逐个绘制圆 initX = w / 2; @@ -183,19 +184,19 @@ void NavigationProgressBar::drawText(QPainter *painter, const bool ok) double initX = 0; double initY = 0; - QColor color = ok? d->currentBackgroundColor: d->backgroundColor; + QColor color = ok ? d->currentBackgroundColor : d->backgroundColor; painter->setFont(QFont("Microsoft YaHei", h / 4)); painter->setPen(color); painter->setBrush(Qt::NoBrush); - int step = ok ? d->step: d->maxStep; + int step = ok ? d->step : d->maxStep; for (int i = 0; i < step; i++) { QRect textRect(initX, initY, w, h); painter->drawText(textRect, Qt::AlignCenter, d->topInfo.at(i)); initX += w; } - if(ok){ + if (ok) { initX = 0; initY = h * 2; for (int i = 0; i < step; i++) { diff --git a/NavigationProgressBar/navigationprogressbar.h b/NavigationProgressBar/navigationprogressbar.h index cc20d34..95b8bed 100644 --- a/NavigationProgressBar/navigationprogressbar.h +++ b/NavigationProgressBar/navigationprogressbar.h @@ -15,25 +15,25 @@ class NavigationProgressBar : public QWidget Q_PROPERTY(QColor foregroundColor READ foregroundColor WRITE setForegroundColor) public: explicit NavigationProgressBar(QWidget *parent = nullptr); - ~NavigationProgressBar(); + ~NavigationProgressBar() override; - QSize sizeHint() const override; - QSize minimumSizeHint() const override; + [[nodiscard]] auto sizeHint() const -> QSize override; + [[nodiscard]] auto minimumSizeHint() const -> QSize override; void setMessageList(const QStringList &list); - QStringList messageList() const; + [[nodiscard]] auto messageList() const -> QStringList; void setStep(const int step); - int step() const; + [[nodiscard]] auto step() const -> int; void setBackgroundColor(const QColor &color); - QColor backgroundColor() const; + [[nodiscard]] auto backgroundColor() const -> QColor; void setCurrentBackgroundColor(const QColor &color); - QColor currentBackgroundColor() const; + [[nodiscard]] auto currentBackgroundColor() const -> QColor; void setForegroundColor(const QColor &color); - QColor foregroundColor() const; + [[nodiscard]] auto foregroundColor() const -> QColor; protected: void paintEvent(QPaintEvent *event) override; diff --git a/PasswordLineEdit/main.cc b/PasswordLineEdit/main.cc index e9bbf59..5d48a9d 100644 --- a/PasswordLineEdit/main.cc +++ b/PasswordLineEdit/main.cc @@ -7,7 +7,7 @@ #include #endif -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/PasswordLineEdit/mainwindow.hpp b/PasswordLineEdit/mainwindow.hpp index ddd5081..121a60e 100644 --- a/PasswordLineEdit/mainwindow.hpp +++ b/PasswordLineEdit/mainwindow.hpp @@ -13,8 +13,8 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_HPP diff --git a/ProgressArc/main.cpp b/ProgressArc/main.cpp index fd3e533..24ba3b6 100644 --- a/ProgressArc/main.cpp +++ b/ProgressArc/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/ProgressArc/mainwindow.h b/ProgressArc/mainwindow.h index d147190..b50d227 100644 --- a/ProgressArc/mainwindow.h +++ b/ProgressArc/mainwindow.h @@ -8,7 +8,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_H diff --git a/ProgressArc/progressarc.cpp b/ProgressArc/progressarc.cpp index 1f073a6..46bf40e 100644 --- a/ProgressArc/progressarc.cpp +++ b/ProgressArc/progressarc.cpp @@ -33,7 +33,7 @@ ProgressArc::ProgressArc(const QString &title, QWidget *parent) connect(this, &ProgressArc::valueChanged, this, &ProgressArc::onStartAnimation); } -ProgressArc::~ProgressArc() {} +ProgressArc::~ProgressArc() = default; void ProgressArc::setTitle(const QString &title) { @@ -41,7 +41,7 @@ void ProgressArc::setTitle(const QString &title) update(); } -QString ProgressArc::title() const +auto ProgressArc::title() const -> QString { return d_ptr->title; } @@ -52,7 +52,7 @@ void ProgressArc::setPercent(const bool percent) update(); } -bool ProgressArc::percent() const +auto ProgressArc::percent() const -> bool { return d_ptr->percent; } @@ -63,7 +63,7 @@ void ProgressArc::setMin(const double min) update(); } -double ProgressArc::min() const +auto ProgressArc::min() const -> double { return d_ptr->minValue; } @@ -74,7 +74,7 @@ void ProgressArc::setmax(const double max) update(); } -double ProgressArc::max() const +auto ProgressArc::max() const -> double { return d_ptr->maxValue; } @@ -85,7 +85,7 @@ void ProgressArc::setStartAngle(const double startAngle) update(); } -double ProgressArc::startAngle() const +auto ProgressArc::startAngle() const -> double { return d_ptr->startAngle; } @@ -96,7 +96,7 @@ void ProgressArc::setEndAngle(const double endAngle) update(); } -double ProgressArc::endAngle() const +auto ProgressArc::endAngle() const -> double { return d_ptr->endAngle; } @@ -107,7 +107,7 @@ void ProgressArc::setArcColor(const QColor &color) update(); } -QColor ProgressArc::arcColor() const +auto ProgressArc::arcColor() const -> QColor { return d_ptr->arcColor; } @@ -118,7 +118,7 @@ void ProgressArc::setTextColor(const QColor &color) update(); } -QColor ProgressArc::textColor() const +auto ProgressArc::textColor() const -> QColor { return d_ptr->textColor; } @@ -129,7 +129,7 @@ void ProgressArc::setTitleColor(const QColor &color) update(); } -QColor ProgressArc::titleColor() const +auto ProgressArc::titleColor() const -> QColor { return d_ptr->titleColor; } @@ -140,7 +140,7 @@ void ProgressArc::setBaseColor(const QColor &color) update(); } -QColor ProgressArc::baseColor() const +auto ProgressArc::baseColor() const -> QColor { return d_ptr->baseColor; } @@ -151,19 +151,19 @@ void ProgressArc::setBackgroundColor(const QColor &color) update(); } -QColor ProgressArc::backgroundColor() const +auto ProgressArc::backgroundColor() const -> QColor { return d_ptr->backgroundColor; } -QSize ProgressArc::sizeHint() const +auto ProgressArc::sizeHint() const -> QSize { - return QSize(200, 200); + return {200, 200}; } -QSize ProgressArc::minimumSizeHint() const +auto ProgressArc::minimumSizeHint() const -> QSize { - return QSize(80, 80); + return {80, 80}; } void ProgressArc::paintEvent(QPaintEvent *event) @@ -190,8 +190,9 @@ void ProgressArc::paintEvent(QPaintEvent *event) void ProgressArc::onStartAnimation(const double value) { - if (value < d_ptr->minValue || value > d_ptr->maxValue || value == d_ptr->value) + if (value < d_ptr->minValue || value > d_ptr->maxValue || value == d_ptr->value) { return; +} int start = d_ptr->value; int end = value; @@ -201,7 +202,7 @@ void ProgressArc::onStartAnimation(const double value) d_ptr->animation->start(); } -double ProgressArc::value() const +auto ProgressArc::value() const -> double { return d_ptr->value; } diff --git a/ProgressArc/progressarc.h b/ProgressArc/progressarc.h index 321e3ba..30b8dc8 100644 --- a/ProgressArc/progressarc.h +++ b/ProgressArc/progressarc.h @@ -20,46 +20,46 @@ class ProgressArc : public QWidget Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor) public: explicit ProgressArc(const QString &title, QWidget *parent = nullptr); - ~ProgressArc(); + ~ProgressArc() override; - QSize sizeHint() const override; - QSize minimumSizeHint() const override; + [[nodiscard]] auto sizeHint() const -> QSize override; + [[nodiscard]] auto minimumSizeHint() const -> QSize override; - double value() const; + [[nodiscard]] auto value() const -> double; void setValue(const double value); void setTitle(const QString &title); - QString title() const; + [[nodiscard]] auto title() const -> QString; void setPercent(const bool percent); - bool percent() const; + [[nodiscard]] auto percent() const -> bool; void setMin(const double min); - double min() const; + [[nodiscard]] auto min() const -> double; void setmax(const double max); - double max() const; + [[nodiscard]] auto max() const -> double; void setStartAngle(const double startAngle); - double startAngle() const; + [[nodiscard]] auto startAngle() const -> double; void setEndAngle(const double endAngle); - double endAngle() const; + [[nodiscard]] auto endAngle() const -> double; void setArcColor(const QColor &color); - QColor arcColor() const; + [[nodiscard]] auto arcColor() const -> QColor; void setTextColor(const QColor &color); - QColor textColor() const; + [[nodiscard]] auto textColor() const -> QColor; void setTitleColor(const QColor &color); - QColor titleColor() const; + [[nodiscard]] auto titleColor() const -> QColor; void setBaseColor(const QColor &color); - QColor baseColor() const; + [[nodiscard]] auto baseColor() const -> QColor; void setBackgroundColor(const QColor &color); - QColor backgroundColor() const; + [[nodiscard]] auto backgroundColor() const -> QColor; signals: void valueChanged(const double value); diff --git a/ProgressBar/main.cc b/ProgressBar/main.cc index e9bbf59..5d48a9d 100644 --- a/ProgressBar/main.cc +++ b/ProgressBar/main.cc @@ -7,7 +7,7 @@ #include #endif -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/ProgressBar/mainwindow.hpp b/ProgressBar/mainwindow.hpp index fbb650e..695b56b 100644 --- a/ProgressBar/mainwindow.hpp +++ b/ProgressBar/mainwindow.hpp @@ -13,7 +13,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_HPP diff --git a/ProgressBar/progressbar.cc b/ProgressBar/progressbar.cc index 4960b5b..48f0dbd 100644 --- a/ProgressBar/progressbar.cc +++ b/ProgressBar/progressbar.cc @@ -30,16 +30,16 @@ ProgressBar::ProgressBar(QWidget *parent) connect(this, &ProgressBar::valueChanged, this, &ProgressBar::onStartAnimation); } -ProgressBar::~ProgressBar() {} +ProgressBar::~ProgressBar() = default; -QSize ProgressBar::sizeHint() const +auto ProgressBar::sizeHint() const -> QSize { - return QSize(165, 15); + return {165, 15}; } -QSize ProgressBar::minimumSizeHint() const +auto ProgressBar::minimumSizeHint() const -> QSize { - return QSize(100, 15); + return {100, 15}; } void ProgressBar::setValue(const double value) @@ -48,7 +48,7 @@ void ProgressBar::setValue(const double value) update(); } -double ProgressBar::value() const +auto ProgressBar::value() const -> double { return d_ptr->value; } @@ -59,7 +59,7 @@ void ProgressBar::setPercent(const bool percent) update(); } -bool ProgressBar::percent() const +auto ProgressBar::percent() const -> bool { return d_ptr->percent; } @@ -70,7 +70,7 @@ void ProgressBar::setMin(const double min) update(); } -double ProgressBar::min() const +auto ProgressBar::min() const -> double { return d_ptr->minValue; } @@ -81,7 +81,7 @@ void ProgressBar::setmax(const double max) update(); } -double ProgressBar::max() const +auto ProgressBar::max() const -> double { return d_ptr->maxValue; } @@ -92,7 +92,7 @@ void ProgressBar::setRadius(const double radius) update(); } -double ProgressBar::radius() const +auto ProgressBar::radius() const -> double { return d_ptr->radius; } @@ -103,7 +103,7 @@ void ProgressBar::setAutoRadius(bool autoRadius) update(); } -double ProgressBar::autoRadius() const +auto ProgressBar::autoRadius() const -> double { return d_ptr->autoRadius; } @@ -114,7 +114,7 @@ void ProgressBar::setChunkColor(const QColor &color) update(); } -QColor ProgressBar::chunkColor() const +auto ProgressBar::chunkColor() const -> QColor { return d_ptr->chunkColor; } @@ -125,7 +125,7 @@ void ProgressBar::setTextColor(const QColor &color) update(); } -QColor ProgressBar::textColor() const +auto ProgressBar::textColor() const -> QColor { return d_ptr->textColor; } @@ -136,7 +136,7 @@ void ProgressBar::setBaseColor(const QColor &color) update(); } -QColor ProgressBar::baseColor() const +auto ProgressBar::baseColor() const -> QColor { return d_ptr->baseColor; } @@ -147,15 +147,16 @@ void ProgressBar::setBackgroundColor(const QColor &color) update(); } -QColor ProgressBar::backgroundColor() const +auto ProgressBar::backgroundColor() const -> QColor { return d_ptr->backgroundColor; } void ProgressBar::onStartAnimation(const double value) { - if (value < d_ptr->minValue || value > d_ptr->maxValue || value == d_ptr->value) + if (value < d_ptr->minValue || value > d_ptr->maxValue || value == d_ptr->value) { return; +} int start = d_ptr->value; int end = value; diff --git a/ProgressBar/progressbar.hpp b/ProgressBar/progressbar.hpp index 847ab48..50c43f9 100644 --- a/ProgressBar/progressbar.hpp +++ b/ProgressBar/progressbar.hpp @@ -23,40 +23,40 @@ class ProgressBar : public QWidget Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor) public: explicit ProgressBar(QWidget *parent = nullptr); - ~ProgressBar(); + ~ProgressBar() override; - QSize sizeHint() const override; - QSize minimumSizeHint() const override; + [[nodiscard]] auto sizeHint() const -> QSize override; + [[nodiscard]] auto minimumSizeHint() const -> QSize override; void setValue(const double value); - double value() const; + [[nodiscard]] auto value() const -> double; void setPercent(const bool percent); - bool percent() const; + [[nodiscard]] auto percent() const -> bool; void setMin(const double min); - double min() const; + [[nodiscard]] auto min() const -> double; void setmax(const double max); - double max() const; + [[nodiscard]] auto max() const -> double; void setRadius(const double radius); - double radius() const; + [[nodiscard]] auto radius() const -> double; void setAutoRadius(bool autoRadius); - double autoRadius() const; + [[nodiscard]] auto autoRadius() const -> double; void setChunkColor(const QColor &color); - QColor chunkColor() const; + [[nodiscard]] auto chunkColor() const -> QColor; void setTextColor(const QColor &color); - QColor textColor() const; + [[nodiscard]] auto textColor() const -> QColor; void setBaseColor(const QColor &color); - QColor baseColor() const; + [[nodiscard]] auto baseColor() const -> QColor; void setBackgroundColor(const QColor &color); - QColor backgroundColor() const; + [[nodiscard]] auto backgroundColor() const -> QColor; signals: void valueChanged(const double value); diff --git a/README.md b/README.md index 11e93e1..32b6266 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ - [简体中文](README.md) - [English](README.en.md) -## 1. [Battery](Battery/)——电池; +## [Battery](Battery/)——电池; @@ -12,40 +12,40 @@
-## 2. [BubbleWindow](BubbleWindow/)——气泡式对话框,也可作工具提示(ToolTip); +## [BubbleWindow](BubbleWindow/)——气泡式对话框,也可作工具提示(ToolTip);
-## 3. [Chart](Chart/)——可视化图表绘制,参考[ 使用 QChart 显示实时动态曲线 ](https://qtdebug.com/qtbook-paint-realtime-curve-qchart/ "qtdebug/公孙二狗") 和QChart相关示例; +## [Chart](Chart/)——可视化图表绘制,参考[ 使用 QChart 显示实时动态曲线 ](https://qtdebug.com/qtbook-paint-realtime-curve-qchart/ "qtdebug/公孙二狗") 和QChart相关示例;
图一二是动态曲线
图一二是动态曲线, 图二坐标轴也会动态变化
-## 4. [CheckBoxStandardItem](/CheckBoxStandardItem)——可勾选StandardItem; +## [CheckBoxStandardItem](/CheckBoxStandardItem)——可以勾选的StandardItem,而且根据勾选状态自动更新父节点状态或者子节点状态;
-## 5. [Clock](/Clock)——时钟; +## [Clock](/Clock)——时钟;
-## 6. [DashBoard](/DashBoard)——仪表盘; +## [DashBoard](/DashBoard)——仪表盘;
-## 7. [FlowLayout](FlowLayout/)——流式布局,来自QT示例Flow Layout Example; +## [FlowLayout](FlowLayout/)——流式布局,来自QT示例Flow Layout Example;
-## 8. [DragDrop](DragDrop/)——简单控件拖拽,参考QT示例Drag and Drop Puzzle Example; +## [DragDrop](DragDrop/)——简单控件拖拽,参考QT示例Drag and Drop Puzzle Example; -## 9. [HttpClient ](/HttpClient)——http客户端; +## [HttpClient ](/HttpClient)——http客户端; -## 10. [GridViewModel ](/GridViewModel)——基于QListView的自适应宫图; +## [GridViewModel ](/GridViewModel)——基于QListView的自适应宫图;
-## 11. [LogAsynchronous](LogAsynchronous/)——异步日志,开辟一个线程专门往文件里写日志,前后端分离。 +## [LogAsynchronous](LogAsynchronous/)——异步日志,开辟一个线程专门往文件里写日志,前后端分离。 1. 日志文件名:应用程序名(appname).时间(time,精确到秒).主机hostname.进程ID(Tid).log(.count),假如一天内写的单个日志大约接近1G,会自动加后缀(.1,.2.3...,以此类推)新建新的日志文件去写,每天0点依然会rollFile; 1. 正常文件名:LogAsynchronous.2020-04-26-20-29-03.Youth.11828.log; @@ -53,15 +53,15 @@ 2. 日志格式:时间(time,精确到毫秒).线程ID(Pid).日志级别(debug).打印信息(msg).文件(File).行号(Line)。 1. 比如:2020-04-26 20:38:55.818 2052 [Debug] 123456789qwertyuioplkjhgfdsa 8412789-File:(..\logAsynchronous\main.cpp) Line:(19); -## 12. [MulClient](MulClient/)——多线程客户端,一个线程一个客户端(怎么可以绕开系统限制,模拟百万个客户端); +## [MulClient](MulClient/)——多线程客户端,一个线程一个客户端(怎么可以绕开系统限制,模拟百万个客户端); -## 13. [MulServer](MulServer/)——多线程服务端,一个线程一个客户端处理(处理实时性很高的TCP通讯); +## [MulServer](MulServer/)——多线程服务端,一个线程一个客户端处理(处理实时性很高的TCP通讯); -## 14. [NavigationProgressBar](/NavigationProgressBar)——导航进度栏; +## [NavigationProgressBar](/NavigationProgressBar)——导航进度栏;
-## 15. [PasswordLineEdit](PasswordLineEdit/)——密码输入框; +## [PasswordLineEdit](PasswordLineEdit/)——密码输入框; @@ -70,21 +70,21 @@
-## 16. [ProgressArc](ProgressArc/)——圆弧进度条; +## [ProgressArc](ProgressArc/)——圆弧进度条;
-## 17. [ProgressBar](ProgressBar)——QProgressBar圆角替代方案; +## [ProgressBar](ProgressBar)——QProgressBar圆角替代方案;
-## 18. [ReactorServer](ReactorServer/)——多线程服务端,Reactor模式(Echo); +## [ReactorServer](ReactorServer/)——多线程服务端,Reactor模式(Echo); -## 19. [SimpleUdp](SimpleUdp/)——简单UDP例子,广播和接收; +## [SimpleUdp](SimpleUdp/)——简单UDP例子,广播和接收; 防火墙白名单。 -## 20. [SlipButton](SlipButton/)——滑动按钮; +## [SlipButton](SlipButton/)——滑动按钮; 另:更简单的实现:[有动画效果的 CheckBox](http://qtdebug.com/qtbook-animated-checkbox/); @@ -95,24 +95,30 @@ -## 21. [SqlTabview](SqlTabview/)——SQLite数据库调用,模型方法; +## [SqlTabview](SqlTabview/)——SQLite数据库调用,模型方法; -## 22. [TableViewModel](TableViewModel/)——表格视图,DeleGate(Button and ProgressBar)(MVC); +## [TableViewModel](TableViewModel/)——表格视图; - 套用了旧的样式(懒),具体可以自己调整; +1. 各种自定义代理 + 1. [ButtonDelegate](./TableViewModel/buttondelegate.h); + 2. [ComboBoxDelegate](./TableViewModel/comboboxdelegate.h); + 3. [ProgressBarDelegate](./TableViewModel/progressbardelegate.h); + 4. [RichTextItemDelegate](./TableViewModel/richtextitemdelegate.hpp); + 5. [StarDelegate](./TableViewModel/stardelegate.h)----来自Qt示例Star Delegate Example; +2. 十万级数据渲染; -
+
-## 23. [Thread](Thread/)——多线程例子,6种写法; +## [Thread](Thread/)——多线程例子,6种写法; -## 24. [TreeViewModel](TreeViewModel/)——树形视图(MVC),QtCreator源码; +## [TreeViewModel](TreeViewModel/)——树形视图(MVC),QtCreator源码;
-## 25. [Validator](Validator/)——加强版IntValidator(QIntValidator)和DoubleValidator(QDoubleValidator) +## [Validator](Validator/)——加强版IntValidator(QIntValidator)和DoubleValidator(QDoubleValidator) -## 26. [Scripts](Scripts/)——打包脚本 +## [Scripts](Scripts/)——打包脚本 1. [macos](Scripts/macos/)——macos 通用编译打dmg包脚本(`python`/`dmgbuild`); 2. [widnows](Scripts/windows)——windows 通用编译打包安装脚本(Innosetup); diff --git a/ReactorServer/main.cpp b/ReactorServer/main.cpp index fd3e533..24ba3b6 100644 --- a/ReactorServer/main.cpp +++ b/ReactorServer/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/ReactorServer/mainwindow.cpp b/ReactorServer/mainwindow.cpp index 73b64e4..445928d 100644 --- a/ReactorServer/mainwindow.cpp +++ b/ReactorServer/mainwindow.cpp @@ -7,7 +7,7 @@ class MainWindowPrivate { public: - MainWindowPrivate(QMainWindow* owner) : owner(owner){ + explicit MainWindowPrivate(QMainWindow* owner) : owner(owner){ ipBox = new QComboBox(owner); portEdit = new QLineEdit(owner); threadSpinBox = new QSpinBox(owner); diff --git a/ReactorServer/mainwindow.h b/ReactorServer/mainwindow.h index d526548..84f9a8c 100644 --- a/ReactorServer/mainwindow.h +++ b/ReactorServer/mainwindow.h @@ -9,8 +9,8 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private slots: void onListen(bool); diff --git a/ReactorServer/subreactor.h b/ReactorServer/subreactor.h index 8776d52..c4a9f44 100644 --- a/ReactorServer/subreactor.h +++ b/ReactorServer/subreactor.h @@ -7,8 +7,8 @@ class SubReactor : public QObject { Q_OBJECT public: - SubReactor(QObject *parent = nullptr); - ~SubReactor(); + explicit SubReactor(QObject *parent = nullptr); + ~SubReactor() override; signals: void message(const QString&); diff --git a/ReactorServer/tcpclient.cpp b/ReactorServer/tcpclient.cpp index d8bb39d..e99a100 100644 --- a/ReactorServer/tcpclient.cpp +++ b/ReactorServer/tcpclient.cpp @@ -12,7 +12,7 @@ TcpClient::~TcpClient() qDebug() << "~TcpSocket"; } -QString TcpClient::getInfo() const +auto TcpClient::getInfo() const -> QString { QString info = peerName() + " " + peerAddress().toString() + " " + QString::number(peerPort()) + " "; diff --git a/ReactorServer/tcpclient.h b/ReactorServer/tcpclient.h index 1fe3fcb..f41c2de 100644 --- a/ReactorServer/tcpclient.h +++ b/ReactorServer/tcpclient.h @@ -7,10 +7,10 @@ class TcpClient : public QTcpSocket { Q_OBJECT public: - TcpClient(QObject *parent = nullptr); - ~TcpClient(); + explicit TcpClient(QObject *parent = nullptr); + ~TcpClient() override; - QString getInfo() const; + [[nodiscard]] auto getInfo() const -> QString; public slots: void onReadyRead(); diff --git a/ReactorServer/tcpserver.cpp b/ReactorServer/tcpserver.cpp index 6a02013..b239624 100644 --- a/ReactorServer/tcpserver.cpp +++ b/ReactorServer/tcpserver.cpp @@ -1,23 +1,27 @@ #include "tcpserver.h" -#include "thread.h" #include "subreactor.h" +#include "thread.h" -class TcpServerPrivate{ +class TcpServerPrivate +{ public: - TcpServerPrivate(QObject *parent) : owner(parent) {} + explicit TcpServerPrivate(QObject *parent) + : owner(parent) + {} QObject *owner; - QVector threads; - SubReactor* subReactor = nullptr; + QVector threads; + SubReactor *subReactor = nullptr; int index = 0; }; -TcpServer::TcpServer(int num, QObject *parent) : QTcpServer(parent) - , d(new TcpServerPrivate(this)) +TcpServer::TcpServer(int num, QObject *parent) + : QTcpServer(parent) + , d(new TcpServerPrivate(this)) { qRegisterMetaType("qintptr"); qRegisterMetaType("QAtomicInt"); - for(int i=0; istart(); } - if(num <= 0){ // one Thread in Accepter + if (num <= 0) { // one Thread in Accepter d->subReactor = new SubReactor(this); connect(d->subReactor, &SubReactor::message, this, &TcpServer::message); connect(d->subReactor, &SubReactor::maxCount, this, &TcpServer::maxCount); @@ -36,7 +40,7 @@ TcpServer::TcpServer(int num, QObject *parent) : QTcpServer(parent) TcpServer::~TcpServer() { - if(!d->threads.isEmpty()){ + if (!d->threads.isEmpty()) { qDeleteAll(d->threads); d->threads.clear(); } @@ -49,20 +53,22 @@ TcpServer::~TcpServer() //------------------------------------------------- void TcpServer::incomingConnection(qintptr handle) { - Thread *thread = getNextThread(); - if(thread != nullptr) + auto thread = getNextThread(); + if (thread != nullptr) { emit thread->newConnectHandle(handle); - else if(d->subReactor != nullptr) + } else if (d->subReactor != nullptr) { d->subReactor->onNewConnect(handle); + } } -Thread *TcpServer::getNextThread() +auto TcpServer::getNextThread() -> Thread * { - if(d->threads.isEmpty()) + if (d->threads.isEmpty()) { return nullptr; - if(d->index < 0 || d->index >= d->threads.size()) + } + if (d->index < 0 || d->index >= d->threads.size()) d->index = 0; - Thread* thread = d->threads.at(d->index); + Thread *thread = d->threads.at(d->index); d->index++; return thread; } diff --git a/ReactorServer/tcpserver.h b/ReactorServer/tcpserver.h index ee80d94..786b4f6 100644 --- a/ReactorServer/tcpserver.h +++ b/ReactorServer/tcpserver.h @@ -10,7 +10,7 @@ class TcpServer : public QTcpServer { Q_OBJECT public: - TcpServer(int num = 10, QObject *parent = nullptr); + explicit TcpServer(int num = 10, QObject *parent = nullptr); ~TcpServer() override; signals: @@ -23,7 +23,7 @@ class TcpServer : public QTcpServer private: void createSocket(qintptr); - Thread* getNextThread(); + auto getNextThread() -> Thread*; QScopedPointer d; }; diff --git a/ReactorServer/thread.h b/ReactorServer/thread.h index e72239e..26e8f21 100644 --- a/ReactorServer/thread.h +++ b/ReactorServer/thread.h @@ -8,7 +8,7 @@ class Thread : public QThread { Q_OBJECT public: - Thread(QObject *parent = nullptr); + explicit Thread(QObject *parent = nullptr); ~Thread() override; signals: diff --git a/SlipButton/main.cpp b/SlipButton/main.cpp index fd3e533..24ba3b6 100644 --- a/SlipButton/main.cpp +++ b/SlipButton/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/SlipButton/mainwindow.h b/SlipButton/mainwindow.h index d147190..b50d227 100644 --- a/SlipButton/mainwindow.h +++ b/SlipButton/mainwindow.h @@ -8,7 +8,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; #endif // MAINWINDOW_H diff --git a/SlipButton/slipbutton.h b/SlipButton/slipbutton.h index 972f77d..448d556 100644 --- a/SlipButton/slipbutton.h +++ b/SlipButton/slipbutton.h @@ -8,36 +8,38 @@ class SlipButton : public QAbstractButton { Q_OBJECT Q_PROPERTY(int offset READ offset WRITE setOffset) - Q_PROPERTY(QColor checkedBackgroundColor READ checkedBackgroundColor WRITE setCheckedBackgroundColor) - Q_PROPERTY(QColor uncheckedBackgroundColor READ uncheckedBackgroundColor WRITE setUncheckedBackgroundColor) + Q_PROPERTY( + QColor checkedBackgroundColor READ checkedBackgroundColor WRITE setCheckedBackgroundColor) + Q_PROPERTY(QColor uncheckedBackgroundColor READ uncheckedBackgroundColor WRITE + setUncheckedBackgroundColor) public: - explicit SlipButton(QWidget* parent = nullptr); + explicit SlipButton(QWidget *parent = nullptr); ~SlipButton() override; - QSize sizeHint() const override; - QSize minimumSizeHint() const override; + [[nodiscard]] auto sizeHint() const -> QSize override; + [[nodiscard]] auto minimumSizeHint() const -> QSize override; public slots: void setCheckedBackgroundColor(const QColor &color); - QColor checkedBackgroundColor() const; + [[nodiscard]] auto checkedBackgroundColor() const -> QColor; void setUncheckedBackgroundColor(const QColor &color); - QColor uncheckedBackgroundColor() const; + [[nodiscard]] auto uncheckedBackgroundColor() const -> QColor; protected: - void paintEvent(QPaintEvent* event) override; + void paintEvent(QPaintEvent *event) override; void enterEvent(QEnterEvent *event) override; - void leaveEvent(QEvent* event) override; - void resizeEvent(QResizeEvent* event) override; + void leaveEvent(QEvent *event) override; + void resizeEvent(QResizeEvent *event) override; private slots: void onStartAnimation(); - int offset() const; + [[nodiscard]] auto offset() const -> int; void setOffset(int offset); private: - inline double widthMargin() const; - inline double heightMargin() const; + [[nodiscard]] inline auto widthMargin() const -> double; + [[nodiscard]] inline auto heightMargin() const -> double; QScopedPointer d; }; diff --git a/SqlTabview/main.cpp b/SqlTabview/main.cpp index fd3e533..24ba3b6 100644 --- a/SqlTabview/main.cpp +++ b/SqlTabview/main.cpp @@ -2,7 +2,7 @@ #include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/SqlTabview/mainwindow.cpp b/SqlTabview/mainwindow.cpp index 9b6267b..30b6efa 100644 --- a/SqlTabview/mainwindow.cpp +++ b/SqlTabview/mainwindow.cpp @@ -7,7 +7,7 @@ class MainWindowPrivate{ public: - MainWindowPrivate(QWidget *parent) + explicit MainWindowPrivate(QWidget *parent) :owner(parent){ sqlTabView = new QTableView(owner); sqlTabView->setAlternatingRowColors(true); diff --git a/SqlTabview/mainwindow.h b/SqlTabview/mainwindow.h index 9952b2f..4769884 100644 --- a/SqlTabview/mainwindow.h +++ b/SqlTabview/mainwindow.h @@ -10,8 +10,8 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; private slots: void onAdd(); diff --git a/SqlTabview/sql.h b/SqlTabview/sql.h index 86b939a..e478d83 100644 --- a/SqlTabview/sql.h +++ b/SqlTabview/sql.h @@ -11,8 +11,8 @@ class Sql : public QObject public: explicit Sql(QObject *parent = nullptr); - static bool searchSQLite(QWidget* parent = nullptr); - QSqlError createOrOpenSqlite(); + static auto searchSQLite(QWidget* parent = nullptr) -> bool; + auto createOrOpenSqlite() -> QSqlError; signals: diff --git a/TableViewModel/CMakeLists.txt b/TableViewModel/CMakeLists.txt index 6edcae0..d677841 100644 --- a/TableViewModel/CMakeLists.txt +++ b/TableViewModel/CMakeLists.txt @@ -1,23 +1,29 @@ set(PROJECT_SOURCES - main.cpp - mainwindow.cpp - mainwindow.h - buttondelegate.h - buttondelegate.cpp - comboboxdelegate.h - comboboxdelegate.cpp - progressbardelegate.h - progressbardelegate.cpp - richtextitemdelegate.hpp - richtextitemdelegate.cc - sortfilterproxymodel.h - sortfilterproxymodel.cpp - student.h - studenttablemodel.h - studenttablemodel.cpp - stuedenttable.h - stuedenttable.cpp) + main.cpp + mainwindow.cpp + mainwindow.h + buttondelegate.h + buttondelegate.cpp + comboboxdelegate.h + comboboxdelegate.cpp + displaydata.hpp + displaytablemodel.hpp + displaytablemodel.cc + displaytableview.hpp + displaytableview.cc + progressbardelegate.h + progressbardelegate.cpp + richtextitemdelegate.hpp + richtextitemdelegate.cc + sortfilterproxymodel.h + sortfilterproxymodel.cpp + stardelegate.cpp + stardelegate.h + stareditor.cpp + stareditor.h + starrating.cpp + starrating.h) qt_add_executable(TableViewModel MANUAL_FINALIZATION ${PROJECT_SOURCES}) target_link_libraries(TableViewModel PRIVATE Qt6::Widgets) -qt_finalize_executable(TableViewModel) \ No newline at end of file +qt_finalize_executable(TableViewModel) diff --git a/TableViewModel/TableViewModel.pro b/TableViewModel/TableViewModel.pro index 7e5f253..7dd0f2c 100644 --- a/TableViewModel/TableViewModel.pro +++ b/TableViewModel/TableViewModel.pro @@ -18,24 +18,30 @@ DEFINES += QT_DEPRECATED_WARNINGS SOURCES += \ buttondelegate.cpp \ comboboxdelegate.cpp \ + displaytablemodel.cc \ + displaytableview.cc \ main.cpp \ mainwindow.cpp \ progressbardelegate.cpp \ richtextitemdelegate.cc \ sortfilterproxymodel.cpp \ - studenttablemodel.cpp \ - stuedenttable.cpp + stardelegate.cpp \ + stareditor.cpp \ + starrating.cpp HEADERS += \ buttondelegate.h \ comboboxdelegate.h \ + displaydata.hpp \ + displaytablemodel.hpp \ + displaytableview.hpp \ mainwindow.h \ progressbardelegate.h \ richtextitemdelegate.hpp \ sortfilterproxymodel.h \ - student.h \ - studenttablemodel.h \ - stuedenttable.h + stardelegate.h \ + stareditor.h \ + starrating.h # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin diff --git a/TableViewModel/buttondelegate.cpp b/TableViewModel/buttondelegate.cpp index 4127217..a222d30 100644 --- a/TableViewModel/buttondelegate.cpp +++ b/TableViewModel/buttondelegate.cpp @@ -1,17 +1,17 @@ #include "buttondelegate.h" -#include "student.h" +#include "displaydata.hpp" -#include #include #include +#include #include ButtonDelegate::ButtonDelegate(QObject *parent) : QStyledItemDelegate(parent) , m_buttonPtr(new QStyleOptionButton) -{ - -} +{} + +ButtonDelegate::~ButtonDelegate() {} void ButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, @@ -43,32 +43,34 @@ bool ButtonDelegate::editorEvent(QEvent *event, int w = qMin(option.rect.width(), option.rect.height()) / 10.0; switch (event->type()) { - case QEvent::MouseButtonPress:{ - QMouseEvent* mouseEvent =(QMouseEvent*)event; + case QEvent::MouseButtonPress: { + QMouseEvent *mouseEvent = (QMouseEvent *) event; if (option.rect.adjusted(w, w, -w, -w).contains(mouseEvent->pos())) { m_buttonPtr->state |= QStyle::State_Sunken; } } break; - case QEvent::MouseButtonRelease:{ - QMouseEvent* mouseEvent =(QMouseEvent*)event; + case QEvent::MouseButtonRelease: { + QMouseEvent *mouseEvent = (QMouseEvent *) event; if (option.rect.adjusted(w, w, -w, -w).contains(mouseEvent->pos())) { m_buttonPtr->state &= (~QStyle::State_Sunken); - Student stu = model->data(index, Qt::UserRole).value(); - QString details = tr("This Student id = %1, name = %2, age = %3, " - "gender = %4, achievement = %5") - .arg(stu.id()) - .arg(stu.name()) - .arg(stu.age()) - .arg(stu.gender()) - .arg(stu.achievement()); - QDialog dialog; - QHBoxLayout *layout = new QHBoxLayout(&dialog); - layout->addWidget(new QLabel(details, &dialog)); - dialog.exec(); + auto data = model->data(index, Qt::UserRole).value(); + auto details = tr("Title: %1\nNumber: %2\nState: %3\nProcess: %4\nRichText: %5") + .arg(data.title()) + .arg(data.number()) + .arg(data.state()) + .arg(data.process()) + .arg(data.richText() + "x"); + + auto w = qobject_cast(model->parent()); + if (w) { + QDialog dialog(w); + QHBoxLayout *layout = new QHBoxLayout(&dialog); + layout->addWidget(new QLabel(details, &dialog)); + dialog.exec(); + } } - } - break; + } break; default: break; } return true; diff --git a/TableViewModel/buttondelegate.h b/TableViewModel/buttondelegate.h index fc0a030..f3a756a 100644 --- a/TableViewModel/buttondelegate.h +++ b/TableViewModel/buttondelegate.h @@ -6,16 +6,18 @@ class ButtonDelegate : public QStyledItemDelegate { public: - ButtonDelegate(QObject* parent = nullptr); + explicit ButtonDelegate(QObject *parent = nullptr); + ~ButtonDelegate() override; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; protected: - bool editorEvent(QEvent *event, QAbstractItemModel *model, + auto editorEvent(QEvent *event, + QAbstractItemModel *model, const QStyleOptionViewItem &option, - const QModelIndex &index) override; + const QModelIndex &index) -> bool override; private: QScopedPointer m_buttonPtr; diff --git a/TableViewModel/comboboxdelegate.cpp b/TableViewModel/comboboxdelegate.cpp index 6f0db2b..935f651 100644 --- a/TableViewModel/comboboxdelegate.cpp +++ b/TableViewModel/comboboxdelegate.cpp @@ -1,5 +1,4 @@ #include "comboboxdelegate.h" -#include "student.h" #include @@ -7,14 +6,16 @@ QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const { - QComboBox *comboBox = new QComboBox(parent); - comboBox->addItems(QStringList() << tr("MALE") << tr("FEMALE")); + static const QStringList items{tr("open"), tr("close")}; + + auto comboBox = new QComboBox(parent); + comboBox->addItems(items); return comboBox; } void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { - QComboBox *comboBox = qobject_cast(editor); + auto comboBox = qobject_cast(editor); comboBox->setCurrentIndex(index.data(Qt::EditRole).toInt()); } @@ -22,6 +23,6 @@ void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { - QComboBox *comboBox = qobject_cast(editor); + auto comboBox = qobject_cast(editor); model->setData(index, comboBox->currentText(), Qt::EditRole); } diff --git a/TableViewModel/comboboxdelegate.h b/TableViewModel/comboboxdelegate.h index 4ac4df4..5e6caa0 100644 --- a/TableViewModel/comboboxdelegate.h +++ b/TableViewModel/comboboxdelegate.h @@ -11,9 +11,9 @@ class ComboBoxDelegate : public QStyledItemDelegate : QStyledItemDelegate(parent) {} - QWidget *createEditor(QWidget *parent, + auto createEditor(QWidget *parent, const QStyleOptionViewItem &, - const QModelIndex &) const Q_DECL_OVERRIDE; + const QModelIndex &) const -> QWidget * Q_DECL_OVERRIDE; void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE; void setModelData(QWidget *editor, QAbstractItemModel *model, diff --git a/TableViewModel/displaydata.hpp b/TableViewModel/displaydata.hpp new file mode 100644 index 0000000..2136d6a --- /dev/null +++ b/TableViewModel/displaydata.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include + +class DisplayData : public QSharedData +{ +public: + DisplayData() = default; + DisplayData(const DisplayData &other) + : QSharedData(other) + , checked(other.checked) + , title(other.title) + , number(other.number) + , state(other.state) + , process(other.process) + , rating(other.rating) + , richText(other.richText) + {} + ~DisplayData() = default; + + bool checked = false; + QString title = QObject::tr("title"); + qint16 number = QRandomGenerator::global()->bounded(100); + QString state = QObject::tr("close"); + qint16 process = 50; + int rating = 3; + QString richText = QObject::tr("RichText"); +}; + +class DisplayInfo +{ +public: + DisplayInfo() + : d_ptr(new DisplayData) + {} + + DisplayInfo(bool checked, + const QString &title, + const qint16 number, + const QString &state, + qint16 process, + int rating, + const QString &richText) + : d_ptr(new DisplayData) + { + setChecked(checked); + setTitle(title); + setNumber(number); + setState(state); + setProcess(process); + setRating(rating); + setRichText(richText); + } + + DisplayInfo(const DisplayInfo &other) + : d_ptr(other.d_ptr) + {} + + void setChecked(bool checked) { d_ptr->checked = checked; } + [[nodiscard]] auto checked() const -> bool { return d_ptr->checked; } + + void setTitle(const QString &title) { d_ptr->title = title; } + [[nodiscard]] auto title() const -> QString { return d_ptr->title; } + + void setNumber(const qint16 number) { d_ptr->number = number; } + [[nodiscard]] auto number() const -> qint16 { return d_ptr->number; } + + void setState(const QString &state) { d_ptr->state = state; } + [[nodiscard]] auto state() const -> QString { return d_ptr->state; } + + void setProcess(qint16 process) { d_ptr->process = process; } + [[nodiscard]] auto process() const -> qint16 { return d_ptr->process; } + + void setRating(int rating) { d_ptr->rating = rating; } + [[nodiscard]] auto rating() const -> int { return d_ptr->rating; } + + void setRichText(const QString &richText) { d_ptr->richText = richText; } + [[nodiscard]] auto richText() const -> QString { return d_ptr->richText; } + +private: + QExplicitlySharedDataPointer d_ptr; +}; + +Q_DECLARE_METATYPE(DisplayInfo) diff --git a/TableViewModel/displaytablemodel.cc b/TableViewModel/displaytablemodel.cc new file mode 100644 index 0000000..5ec836b --- /dev/null +++ b/TableViewModel/displaytablemodel.cc @@ -0,0 +1,125 @@ +#include "displaytablemodel.hpp" +#include "starrating.h" + +#include +#include + +DisplayTableModel::DisplayTableModel(QObject *parent) + : QAbstractTableModel(parent) +{ + auto metaEnums = QMetaEnum::fromType(); + for (int i = 0; i < metaEnums.keyCount(); ++i) { + m_headerDatas << metaEnums.key(i); + } +} + +auto DisplayTableModel::data(const QModelIndex &index, int role) const -> QVariant +{ + if (!index.isValid()) { + return {}; + } + + auto row = index.row(); + auto col = index.column(); + + const auto &data = m_datas.at(row); + switch (role) { + case Qt::TextAlignmentRole: return Qt::AlignCenter; + case Qt::CheckStateRole: + if (ID == col) { + return data.checked() ? Qt::Checked : Qt::Unchecked; + } + break; + case Qt::DecorationRole: + if (ID == col) { + return qApp->style()->standardIcon(QStyle::SP_ComputerIcon); + } + break; + case Qt::WhatsThisRole: + case Qt::ToolTipRole: + case Qt::DisplayRole: + case Qt::EditRole: { //双击为空需添加 + switch (col) { + case ID: return row; + case TITLE: return data.title(); + case NUMBER: return data.number(); + case STATE: return data.state(); + case PROCESS: return data.process(); + case RICHTEXT: return data.richText(); + case DETAILS: return tr("Details"); + default: break; + } + break; + case Qt::UserRole: + if (col == RATING) { + return QVariant::fromValue(StarRating(data.rating())); + } + return QVariant::fromValue(data); + } + default: break; + } + return {}; +} + +auto DisplayTableModel::setData(const QModelIndex &index, const QVariant &value, int role) -> bool +{ + if (!index.isValid()) { + return false; + } + + auto row = index.row(); + auto col = index.column(); + + auto data = m_datas.at(row); + switch (role) { + case Qt::CheckStateRole: + if (ID == col) { + data.setChecked(value.toBool()); + } + break; + case Qt::EditRole: { + switch (col) { + case TITLE: data.setTitle(value.toString()); break; + case NUMBER: data.setNumber(value.toInt()); break; + case STATE: data.setState(value.toString()); break; + case PROCESS: data.setProcess(value.toInt()); break; + case RATING: data.setRating(value.value().starCount()); break; + case RICHTEXT: data.setRichText(value.toString()); break; + default: break; + } + } + default: break; + } + emit dataChanged(index, index); + return true; +} + +auto DisplayTableModel::headerData(int section, Qt::Orientation orientation, int role) const + -> QVariant +{ + if (section < 0 || section >= m_headerDatas.size() || orientation != Qt::Horizontal) { + return {}; + } + switch (role) { + case Qt::TextAlignmentRole: return Qt::AlignCenter; + case Qt::WhatsThisRole: + case Qt::ToolTipRole: + case Qt::DisplayRole: return m_headerDatas.at(section); + default: break; + } + return {}; +} + +Qt::ItemFlags DisplayTableModel::flags(const QModelIndex &index) const +{ + if (!index.isValid()) { + return {}; + } + auto flags = QAbstractTableModel::flags(index); + if (index.column() == ID) { + flags |= Qt::ItemIsUserCheckable; + } else { + flags |= Qt::ItemIsEditable; + } + return flags; +} diff --git a/TableViewModel/displaytablemodel.hpp b/TableViewModel/displaytablemodel.hpp new file mode 100644 index 0000000..1039b7e --- /dev/null +++ b/TableViewModel/displaytablemodel.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include "displaydata.hpp" + +#include + +class DisplayTableModel : public QAbstractTableModel +{ + Q_OBJECT +public: + enum Property { ID, TITLE, NUMBER, STATE, PROCESS, RATING, DETAILS, RICHTEXT }; + Q_ENUM(Property); + + explicit DisplayTableModel(QObject *parent = nullptr); + + [[nodiscard]] auto rowCount(const QModelIndex & = QModelIndex()) const -> int + { + return m_datas.size(); + } + [[nodiscard]] auto columnCount(const QModelIndex & = QModelIndex()) const -> int + { + return m_headerDatas.size(); + } + + [[nodiscard]] auto data(const QModelIndex &index, int role = Qt::DisplayRole) const -> QVariant; + auto setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) -> bool; + [[nodiscard]] auto headerData(int section, + Qt::Orientation orientation, + int role = Qt::DisplayRole) const -> QVariant; + [[nodiscard]] auto flags(const QModelIndex &index) const -> Qt::ItemFlags; + + void setDatas(const QVector &datas) + { + beginResetModel(); + m_datas = datas; + endResetModel(); + } + +private: + QVector m_datas; + QStringList m_headerDatas; +}; diff --git a/TableViewModel/displaytableview.cc b/TableViewModel/displaytableview.cc new file mode 100644 index 0000000..2c77df9 --- /dev/null +++ b/TableViewModel/displaytableview.cc @@ -0,0 +1,79 @@ +#include "displaytableview.hpp" +#include "buttondelegate.h" +#include "comboboxdelegate.h" +#include "displaytablemodel.hpp" +#include "progressbardelegate.h" +#include "richtextitemdelegate.hpp" +#include "sortfilterproxymodel.h" +#include "stardelegate.h" + +#include +#include +#include + +class DisplayTableView::DisplayTableViewPrivate +{ +public: + explicit DisplayTableViewPrivate(DisplayTableView *parent) + : q_ptr(parent) + { + model = new DisplayTableModel(q_ptr); + + menu = new QMenu(q_ptr); + menu->addAction(QObject::tr("Insert"), q_ptr, &DisplayTableView::insertItem); + menu->addAction(QObject::tr("Remove"), q_ptr, &DisplayTableView::removeItem); + menu->addAction(QObject::tr("Rename"), q_ptr, [this] { + q_ptr->edit(q_ptr->currentIndex().siblingAtColumn(DisplayTableModel::TITLE)); + }); + } + + DisplayTableView *q_ptr; + + DisplayTableModel *model; + QMenu *menu; +}; + +DisplayTableView::DisplayTableView(QWidget *parent) + : QTableView(parent) + , d_ptr(new DisplayTableViewPrivate(this)) +{ + auto sortModel = new SortFilterProxyModel(this); + sortModel->setSourceModel(d_ptr->model); + setModel(sortModel); + + setShowGrid(true); + setWordWrap(false); + setAlternatingRowColors(true); + verticalHeader()->setVisible(false); + verticalHeader()->setDefaultSectionSize(35); + horizontalHeader()->setStretchLastSection(true); + horizontalHeader()->setDefaultSectionSize(120); + horizontalHeader()->setMinimumSectionSize(60); + horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); + setSelectionBehavior(QAbstractItemView::SelectRows); + setSelectionMode(QAbstractItemView::ExtendedSelection); + setContextMenuPolicy(Qt::DefaultContextMenu); + setSortingEnabled(true); + setIconSize(QSize(20, 20)); + + setItemDelegateForColumn(DisplayTableModel::STATE, new ComboBoxDelegate(this)); + setItemDelegateForColumn(DisplayTableModel::PROCESS, new ProgressBarDelegate(this)); + setItemDelegateForColumn(DisplayTableModel::RATING, new StarDelegate(this)); + setItemDelegateForColumn(DisplayTableModel::RICHTEXT, new RichTextItemDelegate(this)); + setItemDelegateForColumn(DisplayTableModel::DETAILS, new ButtonDelegate(this)); +} + +DisplayTableView::~DisplayTableView() = default; + +void DisplayTableView::setDatas(const QVector &datas) +{ + d_ptr->model->setDatas(datas); +} + +void DisplayTableView::contextMenuEvent(QContextMenuEvent *event) +{ + if (!currentIndex().isValid()) { + return; + } + d_ptr->menu->exec(mapToGlobal(event->pos())); +} diff --git a/TableViewModel/displaytableview.hpp b/TableViewModel/displaytableview.hpp new file mode 100644 index 0000000..830c506 --- /dev/null +++ b/TableViewModel/displaytableview.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "displaydata.hpp" + +#include + +class DisplayTableView : public QTableView +{ + Q_OBJECT +public: + explicit DisplayTableView(QWidget *parent = nullptr); + ~DisplayTableView() override; + + void setDatas(const QVector &datas); + +protected: + void contextMenuEvent(QContextMenuEvent *event) override; + +signals: + void insertItem(); + void removeItem(); + +private: + class DisplayTableViewPrivate; + QScopedPointer d_ptr; +}; diff --git a/TableViewModel/main.cpp b/TableViewModel/main.cpp index ea84d06..2be1a2d 100644 --- a/TableViewModel/main.cpp +++ b/TableViewModel/main.cpp @@ -1,22 +1,11 @@ #include "mainwindow.h" #include -#include -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); - // 套用了旧的样式,具体细节自己调整 - // const QString filePath("D:/Mine/CODE/Qt/Qt-App/resource/qss/base/Common.css"); - // if(QFile::exists(filePath)){ - // QFile file(filePath); - // if(file.open(QFile::ReadOnly)){ - // qApp->setStyleSheet(file.readAll()); - // file.close(); - // } - // } - MainWindow w; w.show(); diff --git a/TableViewModel/mainwindow.cpp b/TableViewModel/mainwindow.cpp index 0c80309..5617780 100644 --- a/TableViewModel/mainwindow.cpp +++ b/TableViewModel/mainwindow.cpp @@ -1,7 +1,5 @@ #include "mainwindow.h" -#include "student.h" -#include "studenttablemodel.h" -#include "stuedenttable.h" +#include "displaytableview.hpp" #include @@ -10,83 +8,96 @@ MainWindow::MainWindow(QWidget *parent) { setupUI(); init(); - resize(800, 300); + resize(1000, 618); } -MainWindow::~MainWindow() -{ -} +MainWindow::~MainWindow() = default; void MainWindow::onInsertItem() { int row = m_table->currentIndex().row(); - Student stu; - stu.setId(m_students.size()); - if (row < 0 || row >= m_students.size()) - m_students.append(stu); - else - m_students.insert(row, stu); + auto data = DisplayInfo{}; + if (row < 0 || row >= m_datas.size()) { + m_datas.append(data); + } else { + m_datas.insert(row, data); + } - m_table->setStudents(m_students); + m_table->setDatas(m_datas); } void MainWindow::onRemoveItem() { QModelIndex index = m_table->currentIndex(); - if (!index.isValid()) + if (!index.isValid()) { return; + } int row = index.row(); - m_students.takeAt(row); - m_table->setStudents(m_students); + m_datas.takeAt(row); + m_table->setDatas(m_datas); } void MainWindow::init() { - m_students.append(Student(true, - 0, - "Jason", - 15, - "MALE", - 66, - 10, - "RRichText1xxxxxxxxxxxxx")); - m_students.append(Student( - false, 1, "Lily", 13, "FEMALE", 85, 20, "RRichText2x")); - m_students.append(Student( - true, 2, "Odin", 16, "FEMALE", 76, 30, "RRichText3x")); - m_students.append(Student(false, - 3, - "Willion", - 12, - "MALE", - 89, - 40, - "RRichText4yyyyyyyyyyyy")); - m_students.append(Student( - true, 4, "Nieo", 14, "MALE", 77, 50, "RRichText5x")); - m_table->setStudents(m_students); - m_table->selectRow(m_students.size() - 1); + m_datas.append({true, + tr("Book"), + static_cast(QRandomGenerator::global()->bounded(100)), + tr("close"), + 50, + 3, + "RRichText1xxxxxxxxxxxxx"}); + m_datas.append( + {false, tr("Pen"), 100, tr("open"), 20, 2, "RRichText2x"}); + m_datas.append({true, + tr("Pencil"), + 200, + tr("close"), + 30, + 1, + "RRichText3x"}); + m_datas.append({false, + tr("Eraser"), + static_cast(QRandomGenerator::global()->bounded(100)), + tr("open"), + 40, + 4, + "RRichText4yyyyyyyyyyyy"}); + m_datas.append({true, + tr("Ruler"), + 500, + tr("close"), + 50, + 5, + "RRichText5x"}); + + while (m_datas.size() < 1000 * 100) { + m_datas.append(m_datas); + } + + m_table->setDatas(m_datas); + m_table->selectRow(m_datas.size() - 1); } void MainWindow::setupUI() { - QPushButton *addBtn = new QPushButton(tr("Add"), this); - QPushButton *removeBtn = new QPushButton(tr("Remove"), this); - m_table = new StudentsTable(this); - QHBoxLayout *hLayout = new QHBoxLayout; + auto addBtn = new QPushButton(tr("Add"), this); + auto removeBtn = new QPushButton(tr("Remove"), this); + m_table = new DisplayTableView(this); + + auto hLayout = new QHBoxLayout; hLayout->addStretch(1); hLayout->addWidget(addBtn); hLayout->addWidget(removeBtn); - QVBoxLayout *layout = new QVBoxLayout; + + auto widget = new QWidget(this); + auto layout = new QVBoxLayout(widget); layout->addLayout(hLayout); layout->addWidget(m_table); - QFrame *frame = new QFrame(this); - frame->setLayout(layout); - setCentralWidget(frame); + setCentralWidget(widget); - connect(m_table, &StudentsTable::insertItem, this, &MainWindow::onInsertItem); - connect(m_table, &StudentsTable::removeItem, this, &MainWindow::onRemoveItem); + connect(m_table, &DisplayTableView::insertItem, this, &MainWindow::onInsertItem); + connect(m_table, &DisplayTableView::removeItem, this, &MainWindow::onRemoveItem); connect(addBtn, &QPushButton::clicked, this, &MainWindow::onInsertItem); connect(removeBtn, &QPushButton::clicked, this, &MainWindow::onRemoveItem); } diff --git a/TableViewModel/mainwindow.h b/TableViewModel/mainwindow.h index fd63dfd..dabc321 100644 --- a/TableViewModel/mainwindow.h +++ b/TableViewModel/mainwindow.h @@ -3,15 +3,14 @@ #include -#include "student.h" +#include "displaydata.hpp" -class StudentsTable; +class DisplayTableView; class MainWindow : public QMainWindow { Q_OBJECT - public: - MainWindow(QWidget *parent = nullptr); + explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: @@ -21,7 +20,9 @@ private slots: private: void init(); void setupUI(); - StudentsTable *m_table; - QVector m_students; + + DisplayTableView *m_table; + QVector m_datas; }; + #endif // MAINWINDOW_H diff --git a/TableViewModel/picture/TabViewModelDelegate.jpg b/TableViewModel/picture/TabViewModelDelegate.jpg new file mode 100644 index 0000000..0195bb7 Binary files /dev/null and b/TableViewModel/picture/TabViewModelDelegate.jpg differ diff --git a/TableViewModel/picture/TabViewModelDelegate.png b/TableViewModel/picture/TabViewModelDelegate.png deleted file mode 100644 index 8a6e9ff..0000000 Binary files a/TableViewModel/picture/TabViewModelDelegate.png and /dev/null differ diff --git a/TableViewModel/progressbardelegate.h b/TableViewModel/progressbardelegate.h index 4439e0a..c76f37f 100644 --- a/TableViewModel/progressbardelegate.h +++ b/TableViewModel/progressbardelegate.h @@ -9,11 +9,11 @@ class ProgressBarDelegate : public QStyledItemDelegate { public: explicit ProgressBarDelegate(QObject *parent = nullptr); - ~ProgressBarDelegate(); + ~ProgressBarDelegate() override; void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const; + const QModelIndex &index) const override; private: QScopedPointer m_progressBarPtr; diff --git a/TableViewModel/richtextitemdelegate.cc b/TableViewModel/richtextitemdelegate.cc index 46fed84..79dcc7c 100644 --- a/TableViewModel/richtextitemdelegate.cc +++ b/TableViewModel/richtextitemdelegate.cc @@ -6,10 +6,10 @@ #include #include -bool textElide(Qt::TextElideMode textElideMode, +auto textElide(Qt::TextElideMode textElideMode, const QFont &font, QTextDocument &doc, - const QRect &rect) + const QRect &rect) -> bool { QFontMetrics fm(font); int dotWidth = fm.horizontalAdvance("..."); @@ -124,8 +124,8 @@ void RichTextItemDelegate::paint(QPainter *painter, painter->restore(); } -QSize RichTextItemDelegate::sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const +auto RichTextItemDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const -> QSize { QStyleOptionViewItem options = option; initStyleOption(&options, index); @@ -133,5 +133,5 @@ QSize RichTextItemDelegate::sizeHint(const QStyleOptionViewItem &option, QTextDocument doc; doc.setHtml(options.text); doc.setTextWidth(options.rect.width()); - return QSize(doc.idealWidth(), doc.size().height()); + return {static_cast(doc.idealWidth()), static_cast(doc.size().height())}; } diff --git a/TableViewModel/richtextitemdelegate.hpp b/TableViewModel/richtextitemdelegate.hpp index ae4a298..665a48f 100644 --- a/TableViewModel/richtextitemdelegate.hpp +++ b/TableViewModel/richtextitemdelegate.hpp @@ -12,7 +12,8 @@ class RichTextItemDelegate : public QStyledItemDelegate void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; + [[nodiscard]] auto sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const + -> QSize override; Qt::TextElideMode textElideMode = Qt::ElideRight; }; diff --git a/TableViewModel/sortfilterproxymodel.cpp b/TableViewModel/sortfilterproxymodel.cpp index 30265bf..e9b286b 100644 --- a/TableViewModel/sortfilterproxymodel.cpp +++ b/TableViewModel/sortfilterproxymodel.cpp @@ -2,7 +2,7 @@ #include -bool SortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const +auto SortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const -> bool { QVariant leftData = sourceModel()->data(left); QVariant rightData = sourceModel()->data(right); diff --git a/TableViewModel/sortfilterproxymodel.h b/TableViewModel/sortfilterproxymodel.h index 34736ba..8d3d71f 100644 --- a/TableViewModel/sortfilterproxymodel.h +++ b/TableViewModel/sortfilterproxymodel.h @@ -6,11 +6,13 @@ class SortFilterProxyModel : public QSortFilterProxyModel { public: - SortFilterProxyModel(QObject *parent = nullptr) - : QSortFilterProxyModel(parent) {} + explicit SortFilterProxyModel(QObject *parent = nullptr) + : QSortFilterProxyModel(parent) + {} protected: - bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; + [[nodiscard]] auto lessThan(const QModelIndex &left, const QModelIndex &right) const + -> bool override; }; #endif // SORTFILTERPROXYMODEL_H diff --git a/TableViewModel/stardelegate.cpp b/TableViewModel/stardelegate.cpp new file mode 100644 index 0000000..f0a0047 --- /dev/null +++ b/TableViewModel/stardelegate.cpp @@ -0,0 +1,90 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include + +#include "stardelegate.h" +#include "stareditor.h" +#include "starrating.h" + +//! [0] +void StarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.data(Qt::UserRole).canConvert()) { + StarRating starRating = qvariant_cast(index.data(Qt::UserRole)); + + if (option.state & QStyle::State_Selected) + painter->fillRect(option.rect, option.palette.highlight()); + + starRating.paint(painter, option.rect, option.palette, + StarRating::EditMode::ReadOnly); + } else { + QStyledItemDelegate::paint(painter, option, index); + } +//! [0] +} + +//! [1] +QSize StarDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.data(Qt::UserRole).canConvert()) { + StarRating starRating = qvariant_cast(index.data(Qt::UserRole)); + return starRating.sizeHint(); + } + return QStyledItemDelegate::sizeHint(option, index); +} +//! [1] + +//! [2] +QWidget *StarDelegate::createEditor(QWidget *parent, + const QStyleOptionViewItem &option, + const QModelIndex &index) const + +{ + if (index.data(Qt::UserRole).canConvert()) { + StarEditor *editor = new StarEditor(parent); + connect(editor, &StarEditor::editingFinished, + this, &StarDelegate::commitAndCloseEditor); + return editor; + } + return QStyledItemDelegate::createEditor(parent, option, index); +} +//! [2] + +//! [3] +void StarDelegate::setEditorData(QWidget *editor, + const QModelIndex &index) const +{ + if (index.data(Qt::UserRole).canConvert()) { + StarRating starRating = qvariant_cast(index.data(Qt::UserRole)); + StarEditor *starEditor = qobject_cast(editor); + starEditor->setStarRating(starRating); + } else { + QStyledItemDelegate::setEditorData(editor, index); + } +} +//! [3] + +//! [4] +void StarDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const +{ + if (index.data(Qt::UserRole).canConvert()) { + StarEditor *starEditor = qobject_cast(editor); + model->setData(index, QVariant::fromValue(starEditor->starRating())); + } else { + QStyledItemDelegate::setModelData(editor, model, index); + } +} +//! [4] + +//! [5] +void StarDelegate::commitAndCloseEditor() +{ + StarEditor *editor = qobject_cast(sender()); + emit commitData(editor); + emit closeEditor(editor); +} +//! [5] diff --git a/TableViewModel/stardelegate.h b/TableViewModel/stardelegate.h new file mode 100644 index 0000000..c5686dd --- /dev/null +++ b/TableViewModel/stardelegate.h @@ -0,0 +1,31 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#ifndef STARDELEGATE_H +#define STARDELEGATE_H + +#include + +//! [0] +class StarDelegate : public QStyledItemDelegate +{ + Q_OBJECT +public: + using QStyledItemDelegate::QStyledItemDelegate; + + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const override; + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; + void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const override; + +private slots: + void commitAndCloseEditor(); +}; +//! [0] + +#endif diff --git a/TableViewModel/stareditor.cpp b/TableViewModel/stareditor.cpp new file mode 100644 index 0000000..8bd3c85 --- /dev/null +++ b/TableViewModel/stareditor.cpp @@ -0,0 +1,63 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include "stareditor.h" +#include "starrating.h" + +#include + +//! [0] +StarEditor::StarEditor(QWidget *parent) + : QWidget(parent) +{ + setMouseTracking(true); + setAutoFillBackground(true); +} +//! [0] + +QSize StarEditor::sizeHint() const +{ + return myStarRating.sizeHint(); +} + +//! [1] +void StarEditor::paintEvent(QPaintEvent *) +{ + QPainter painter(this); + myStarRating.paint(&painter, rect(), palette(), + StarRating::EditMode::Editable); +} +//! [1] + +//! [2] +void StarEditor::mouseMoveEvent(QMouseEvent *event) +{ + const int star = starAtPosition(event->position().toPoint().x()); + + if (star != myStarRating.starCount() && star != -1) { + myStarRating.setStarCount(star); + update(); + } + QWidget::mouseMoveEvent(event); +} +//! [2] + +//! [3] +void StarEditor::mouseReleaseEvent(QMouseEvent *event) +{ + emit editingFinished(); + QWidget::mouseReleaseEvent(event); +} +//! [3] + +//! [4] +int StarEditor::starAtPosition(int x) const +{ + const int star = (x / (myStarRating.sizeHint().width() + / myStarRating.maxStarCount())) + 1; + if (star <= 0 || star > myStarRating.maxStarCount()) + return -1; + + return star; +} +//! [4] diff --git a/TableViewModel/stareditor.h b/TableViewModel/stareditor.h new file mode 100644 index 0000000..bb54190 --- /dev/null +++ b/TableViewModel/stareditor.h @@ -0,0 +1,39 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#ifndef STAREDITOR_H +#define STAREDITOR_H + +#include + +#include "starrating.h" + +//! [0] +class StarEditor : public QWidget +{ + Q_OBJECT +public: + StarEditor(QWidget *parent = nullptr); + + QSize sizeHint() const override; + void setStarRating(const StarRating &starRating) { + myStarRating = starRating; + } + StarRating starRating() { return myStarRating; } + +signals: + void editingFinished(); + +protected: + void paintEvent(QPaintEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + +private: + int starAtPosition(int x) const; + + StarRating myStarRating; +}; +//! [0] + +#endif diff --git a/TableViewModel/starrating.cpp b/TableViewModel/starrating.cpp new file mode 100644 index 0000000..421dc6f --- /dev/null +++ b/TableViewModel/starrating.cpp @@ -0,0 +1,60 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#include "starrating.h" + +#include +#include + +constexpr int PaintingScaleFactor = 20; + +//! [0] +StarRating::StarRating(int starCount, int maxStarCount) + : myStarCount(starCount), + myMaxStarCount(maxStarCount) +{ + starPolygon << QPointF(1.0, 0.5); + for (int i = 1; i < 5; ++i) + starPolygon << QPointF(0.5 + 0.5 * std::cos(0.8 * i * 3.14), + 0.5 + 0.5 * std::sin(0.8 * i * 3.14)); + + diamondPolygon << QPointF(0.4, 0.5) << QPointF(0.5, 0.4) + << QPointF(0.6, 0.5) << QPointF(0.5, 0.6) + << QPointF(0.4, 0.5); +} +//! [0] + +//! [1] +QSize StarRating::sizeHint() const +{ + return PaintingScaleFactor * QSize(myMaxStarCount, 1); +} +//! [1] + +//! [2] +void StarRating::paint(QPainter *painter, const QRect &rect, + const QPalette &palette, EditMode mode) const +{ + painter->save(); + + painter->setRenderHint(QPainter::Antialiasing, true); + painter->setPen(Qt::NoPen); + painter->setBrush(mode == EditMode::Editable ? + palette.highlight() : + palette.windowText()); + + const int yOffset = (rect.height() - PaintingScaleFactor) / 2; + painter->translate(rect.x(), rect.y() + yOffset); + painter->scale(PaintingScaleFactor, PaintingScaleFactor); + + for (int i = 0; i < myMaxStarCount; ++i) { + if (i < myStarCount) + painter->drawPolygon(starPolygon, Qt::WindingFill); + else if (mode == EditMode::Editable) + painter->drawPolygon(diamondPolygon, Qt::WindingFill); + painter->translate(1.0, 0.0); + } + + painter->restore(); +} +//! [2] diff --git a/TableViewModel/starrating.h b/TableViewModel/starrating.h new file mode 100644 index 0000000..31054dd --- /dev/null +++ b/TableViewModel/starrating.h @@ -0,0 +1,39 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause + +#ifndef STARRATING_H +#define STARRATING_H + +#include +#include +#include + +//! [0] +class StarRating +{ +public: + enum class EditMode { Editable, ReadOnly }; + + explicit StarRating(int starCount = 1, int maxStarCount = 5); + + void paint(QPainter *painter, const QRect &rect, + const QPalette &palette, EditMode mode) const; + QSize sizeHint() const; + int starCount() const { return myStarCount; } + int maxStarCount() const { return myMaxStarCount; } + void setStarCount(int starCount) { myStarCount = starCount; } + void setMaxStarCount(int maxStarCount) { myMaxStarCount = maxStarCount; } + +private: + QPolygonF starPolygon; + QPolygonF diamondPolygon; + int myStarCount; + int myMaxStarCount; +}; +//! [0] + +//! [1] +Q_DECLARE_METATYPE(StarRating) +//! [1] + +#endif diff --git a/TableViewModel/student.h b/TableViewModel/student.h deleted file mode 100644 index 05c25fd..0000000 --- a/TableViewModel/student.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef STUDENT_H -#define STUDENT_H - -#include - -class StudentData : public QSharedData -{ -public: - StudentData() {} - StudentData(const StudentData &other) - : QSharedData(other) - , checked(other.checked) - , id(other.id) - , name(other.name) - , age(other.age) - , gender(other.gender) - , achievement(other.achievement) - , process(other.process) - {} - ~StudentData() {} - - bool checked = false; - quint16 id = 0; - QString name; - quint16 age = 0; - QString gender = QObject::tr("MALE"); - quint16 achievement = 0; - qint16 process = 50; - QString richText; -}; - -class Student -{ -public: - Student() - : d_ptr(new StudentData) - {} - Student(bool checked, - quint16 id, - const QString &name, - quint16 age, - const QString &gender, - quint16 achievement, - qint16 process, - const QString &richText) - : d_ptr(new StudentData) - { - setChecked(checked); - setId(id); - setName(name); - setAge(age); - setGender(gender); - setAchievement(achievement); - setProcess(process); - setRichText(richText); - } - Student(const Student &other) - : d_ptr(other.d_ptr) - {} - - void setChecked(bool checked) { d_ptr->checked = checked; } - bool checked() const { return d_ptr->checked; } - - void setId(quint16 id) { d_ptr->id = id; } - quint16 id() const { return d_ptr->id; } - - void setName(const QString &name) { d_ptr->name = name; } - QString name() const { return d_ptr->name; } - - void setAge(quint16 age) { d_ptr->age = age; } - quint16 age() const { return d_ptr->age; } - - void setGender(const QString &gender) { d_ptr->gender = gender; } - QString gender() const { return d_ptr->gender; } - - void setAchievement(quint16 achievement) { d_ptr->achievement = achievement; } - quint16 achievement() const { return d_ptr->achievement; } - - void setProcess(qint16 process) { d_ptr->process = process; } - qint16 process() const { return d_ptr->process; } - - void setRichText(const QString &richText) { d_ptr->richText = richText; } - QString richText() const { return d_ptr->richText; }; - -private: - QExplicitlySharedDataPointer d_ptr; -}; - -Q_DECLARE_METATYPE(Student) - -#endif // STUDENT_H diff --git a/TableViewModel/studenttablemodel.cpp b/TableViewModel/studenttablemodel.cpp deleted file mode 100644 index 9bd95e1..0000000 --- a/TableViewModel/studenttablemodel.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include "studenttablemodel.h" - -#include -#include - -enum Property { ID, NAME, AGE, GENDER, ACHIEVEMENT, MENUBUTTON, PROCESS, RICHTEXT }; - -QVariant StuedentTableModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return false; - - int row = index.row(); - int col = index.column(); - - Student stu = m_students.at(row); - switch (role) { - case Qt::TextAlignmentRole: return Qt::AlignCenter; - case Qt::CheckStateRole: - if (ID == col) { - return stu.checked() ? Qt::Checked : Qt::Unchecked; - } - break; - case Qt::DecorationRole: - if (ID == col) { - return qApp->style()->standardIcon(QStyle::SP_ComputerIcon); - } - break; - case Qt::WhatsThisRole: - case Qt::ToolTipRole: - case Qt::DisplayRole: - case Qt::EditRole: { //双击为空需添加 - switch (col) { - case ID: return stu.id(); - case NAME: return stu.name(); - case AGE: return stu.age(); - case GENDER: return stu.gender(); - case ACHIEVEMENT: return stu.achievement(); - case MENUBUTTON: return tr("Detail"); - case PROCESS: return stu.process(); - case RICHTEXT: return stu.richText(); - default: break; - } - case Qt::UserRole: return QVariant::fromValue(stu); - } - default: break; - } - return QVariant(); -} - -bool StuedentTableModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (!index.isValid()) - return false; - - int row = index.row(); - int col = index.column(); - - Student stu = m_students.at(row); - switch (role) { - case Qt::CheckStateRole: - if (ID == col) { - stu.setChecked(value.toInt()); - emit dataChanged(index, index); - return true; - } - break; - case Qt::EditRole: - switch (col) { - case ID: stu.setId(value.toUInt()); break; - case NAME: stu.setName(value.toString()); break; - case AGE: stu.setAge(value.toUInt()); break; - case GENDER: stu.setGender(value.toString()); break; - case ACHIEVEMENT: stu.setAchievement(value.toUInt()); break; - case PROCESS: stu.setProcess(value.toUInt()); break; - case RICHTEXT: stu.setRichText(value.toString()); break; - } - emit dataChanged(index, index); - return true; - default: break; - } - return false; -} - -QVariant StuedentTableModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - const QStringList names = {tr("ID"), - tr("NAME"), - tr("AGE"), - tr("GENDER"), - tr("ACHIEVEMENT"), - tr("DETAILS"), - tr("PROCESS"), - tr("RICHTEXT")}; - if (section < 0 || section >= names.size()) { - return QVariant(); - } - if (orientation == Qt::Horizontal) { - switch (role) { - case Qt::TextAlignmentRole: return Qt::AlignCenter; - case Qt::WhatsThisRole: - case Qt::ToolTipRole: - case Qt::DisplayRole: return names.at(section); - default: break; - } - } - - return QVariant(); -} - -Qt::ItemFlags StuedentTableModel::flags(const QModelIndex &index) const -{ - Qt::ItemFlags flags = QAbstractTableModel::flags(index); - flags |= Qt::ItemIsEditable; - if (index.column() == ID) { - flags |= Qt::ItemIsUserCheckable; - } - return flags; -} - -void StuedentTableModel::setStudents(const QVector &students) -{ - beginResetModel(); - m_students = students; - endResetModel(); -} diff --git a/TableViewModel/studenttablemodel.h b/TableViewModel/studenttablemodel.h deleted file mode 100644 index 2209a79..0000000 --- a/TableViewModel/studenttablemodel.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef STUDENTTABLEMODEL_H -#define STUDENTTABLEMODEL_H - -#include - -#include "student.h" - -class StuedentTableModel : public QAbstractTableModel -{ - Q_OBJECT -public: - explicit StuedentTableModel(QObject *parent = nullptr) - : QAbstractTableModel(parent) - {} - int rowCount(const QModelIndex & = QModelIndex()) const { return m_students.size(); } - int columnCount(const QModelIndex & = QModelIndex()) const { return 8; } - - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - Qt::ItemFlags flags(const QModelIndex &index) const; - void setStudents(const QVector &students); - -private: - QVector m_students; -}; - -#endif // STUDENTTABLEMODEL_H diff --git a/TableViewModel/stuedenttable.cpp b/TableViewModel/stuedenttable.cpp deleted file mode 100644 index 72f421f..0000000 --- a/TableViewModel/stuedenttable.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "stuedenttable.h" -#include "buttondelegate.h" -#include "comboboxdelegate.h" -#include "progressbardelegate.h" -#include "richtextitemdelegate.hpp" -#include "sortfilterproxymodel.h" -#include "studenttablemodel.h" - -#include - -StudentsTable::StudentsTable(QWidget *parent) - : QTableView(parent) - , m_stuModel(new StuedentTableModel(this)) - , m_menu(new QMenu(this)) -{ - SortFilterProxyModel *sortModel = new SortFilterProxyModel(this); - sortModel->setSourceModel(m_stuModel); - setModel(sortModel); - //setModel(m_stuModel); - - setShowGrid(true); - setWordWrap(false); - setAlternatingRowColors(true); - verticalHeader()->setVisible(false); - verticalHeader()->setDefaultSectionSize(30); - horizontalHeader()->setStretchLastSection(true); - horizontalHeader()->setDefaultSectionSize(90); - horizontalHeader()->setMinimumSectionSize(35); - horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); - setSelectionBehavior(QAbstractItemView::SelectRows); - setSelectionMode(QAbstractItemView::ExtendedSelection); - setContextMenuPolicy(Qt::DefaultContextMenu); - setItemDelegateForColumn(3, new ComboBoxDelegate(this)); - setItemDelegateForColumn(5, new ButtonDelegate(this)); - setItemDelegateForColumn(6, new ProgressBarDelegate(this)); - setItemDelegateForColumn(7, new RichTextItemDelegate(this)); - setSortingEnabled(true); - setIconSize(QSize(20, 20)); - - initMenu(); -} - -void StudentsTable::setStudents(const QVector &students) -{ - m_stuModel->setStudents(students); -} - -void StudentsTable::contextMenuEvent(QContextMenuEvent *event) -{ - if (!currentIndex().isValid()) - return; - m_menu->exec(mapToGlobal(event->pos())); -} - -void StudentsTable::initMenu() -{ - m_menu->addAction(tr("insert"), this, &StudentsTable::insertItem); - m_menu->addAction(tr("remove"), this, &StudentsTable::removeItem); - m_menu->addAction(tr("rename"), this, [this] { edit(currentIndex().siblingAtColumn(0)); }); -} diff --git a/TableViewModel/stuedenttable.h b/TableViewModel/stuedenttable.h deleted file mode 100644 index 7c088b2..0000000 --- a/TableViewModel/stuedenttable.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef STUDENTTABLE_H -#define STUDENTTABLE_H - -#include -#include -#include - -#include "student.h" - -class StuedentTableModel; -class StudentsTable : public QTableView -{ - Q_OBJECT -public: - StudentsTable(QWidget *parent = nullptr); - - void setStudents(const QVector &students); - -protected: - void contextMenuEvent(QContextMenuEvent *event) override; - -signals: - void insertItem(); - void removeItem(); - -private: - void initMenu(); - - StuedentTableModel *m_stuModel; - QMenu *m_menu; -}; - -#endif // STUDENTTABLE_H diff --git a/Thread/functions.hpp b/Thread/functions.hpp index 2478870..31e6ba6 100644 --- a/Thread/functions.hpp +++ b/Thread/functions.hpp @@ -5,7 +5,7 @@ namespace Functions { -QString getCurrentThreadIDStr(); +auto getCurrentThreadIDStr() -> QString; } diff --git a/Thread/main.cc b/Thread/main.cc index d550470..6c350c6 100644 --- a/Thread/main.cc +++ b/Thread/main.cc @@ -3,7 +3,7 @@ #include "thread.hpp" -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QCoreApplication a(argc, argv); diff --git a/Thread/task.hpp b/Thread/task.hpp index 1a68a03..235e6ed 100644 --- a/Thread/task.hpp +++ b/Thread/task.hpp @@ -9,7 +9,7 @@ class Task : public QObject Q_OBJECT public: using QObject::QObject; - ~Task(); + ~Task() override; public slots: void onDo(const QString &text); diff --git a/Thread/thread.hpp b/Thread/thread.hpp index 20b9cf7..e24b85c 100644 --- a/Thread/thread.hpp +++ b/Thread/thread.hpp @@ -20,7 +20,7 @@ class Thread2 : public QThread Q_OBJECT public: using QThread::QThread; - ~Thread2(); + ~Thread2() override; public slots: void onDo(); @@ -36,8 +36,8 @@ class Thread3 : public QObject { Q_OBJECT public: - Thread3(QObject *parent = nullptr); - ~Thread3(); + explicit Thread3(QObject *parent = nullptr); + ~Thread3() override; void dooo(); @@ -53,6 +53,6 @@ void runThread4(); void runThread5(); -QThread *runThread6(); +auto runThread6() -> QThread *; #endif // THREAD_HPP diff --git a/TreeViewModel/checkboxheaderview.hpp b/TreeViewModel/checkboxheaderview.hpp index 4b8ddfd..d76a86a 100644 --- a/TreeViewModel/checkboxheaderview.hpp +++ b/TreeViewModel/checkboxheaderview.hpp @@ -9,7 +9,7 @@ class CheckBoxHeaderView : public QHeaderView public: explicit CheckBoxHeaderView(Qt::Orientation orientation = Qt::Horizontal, QWidget *parent = nullptr); - ~CheckBoxHeaderView(); + ~CheckBoxHeaderView() override; void setState(int state); diff --git a/TreeViewModel/fileinfo.cc b/TreeViewModel/fileinfo.cc index 601d9ce..5c3815f 100644 --- a/TreeViewModel/fileinfo.cc +++ b/TreeViewModel/fileinfo.cc @@ -1,6 +1,6 @@ #include "fileinfo.hpp" -QString bytesToString(qint64 bytes) +auto bytesToString(qint64 bytes) -> QString { static const double KB = 1024 * 1.0; static const double MB = KB * 1024; diff --git a/TreeViewModel/fileinfo.hpp b/TreeViewModel/fileinfo.hpp index 73aca4b..5eb1739 100644 --- a/TreeViewModel/fileinfo.hpp +++ b/TreeViewModel/fileinfo.hpp @@ -5,12 +5,12 @@ #include #include -QString bytesToString(qint64 bytes); +auto bytesToString(qint64 bytes) -> QString; class FileInfoData : public QSharedData { public: - FileInfoData() {} + FileInfoData() = default; FileInfoData(const FileInfoData &other) : QSharedData(other) , fileInfo(other.fileInfo) @@ -37,7 +37,7 @@ class FileInfo : d_ptr(new FileInfoData) {} - FileInfo(const QFileInfo &fileInfo) + explicit FileInfo(const QFileInfo &fileInfo) : d_ptr(new FileInfoData) { setFileInfo(fileInfo); @@ -53,31 +53,31 @@ class FileInfo : d_ptr(other.d_ptr) {} - ~FileInfo() {} + ~FileInfo() = default; - bool operator==(const FileInfo &other) const + auto operator==(const FileInfo &other) const -> bool { return d_ptr->fileInfo == other.d_ptr->fileInfo; } - bool operator!=(const FileInfo &other) const { return !(*this == other); } + auto operator!=(const FileInfo &other) const -> bool { return !(*this == other); } void setFileInfo(const QFileInfo &fileInfo) { d_ptr->fileInfo = fileInfo; } - QFileInfo fileInfo() const { return d_ptr->fileInfo; } + [[nodiscard]] QFileInfo fileInfo() const { return d_ptr->fileInfo; } void setIcon(const QIcon &icon) { d_ptr->icon = icon; } - QIcon icon() const { return d_ptr->icon; } + [[nodiscard]] QIcon icon() const { return d_ptr->icon; } void setType(const QString &type) { d_ptr->type = type; } - QString type() const { return d_ptr->type; } + [[nodiscard]] auto type() const -> QString { return d_ptr->type; } void setModifyTime(const QString &modifyTime) { d_ptr->modifyTime = modifyTime; } - QString modifyTime() const { return d_ptr->modifyTime; } + [[nodiscard]] auto modifyTime() const -> QString { return d_ptr->modifyTime; } void setSize(const QString &size) { d_ptr->size = size; } - QString size() const { return d_ptr->size; } + [[nodiscard]] auto size() const -> QString { return d_ptr->size; } void setChecked(bool checked) { d_ptr->checked = checked; } - bool checked() const { return d_ptr->checked; } + [[nodiscard]] auto checked() const -> bool { return d_ptr->checked; } private: QExplicitlySharedDataPointer d_ptr; diff --git a/TreeViewModel/fileitem.hpp b/TreeViewModel/fileitem.hpp index 57fa978..3ead5d3 100644 --- a/TreeViewModel/fileitem.hpp +++ b/TreeViewModel/fileitem.hpp @@ -9,14 +9,14 @@ class FileInfo; class FileItem : public TreeItem { public: - FileItem(const QFileInfo &fileInfo, bool depth = false); - ~FileItem(); + explicit FileItem(const QFileInfo &fileInfo, bool depth = false); + ~FileItem() override; - QVariant data(int column, int role) const override; - bool setData(int column, const QVariant &data, int role) override; - Qt::ItemFlags flags(int column) const override; + [[nodiscard]] auto data(int column, int role) const -> QVariant override; + auto setData(int column, const QVariant &data, int role) -> bool override; + [[nodiscard]] auto flags(int column) const -> Qt::ItemFlags override; - FileInfo fileInfo() const; + [[nodiscard]] auto fileInfo() const -> FileInfo; private: void init(); diff --git a/TreeViewModel/listview.hpp b/TreeViewModel/listview.hpp index 3726d8b..3d5b9ef 100644 --- a/TreeViewModel/listview.hpp +++ b/TreeViewModel/listview.hpp @@ -10,7 +10,7 @@ class ListView : public TreeView Q_OBJECT public: explicit ListView(QWidget *parent = nullptr); - ~ListView(); + ~ListView() override; void setDatas(const QFileInfoList &fileInfos); diff --git a/TreeViewModel/main.cc b/TreeViewModel/main.cc index e9bbf59..5d48a9d 100644 --- a/TreeViewModel/main.cc +++ b/TreeViewModel/main.cc @@ -7,7 +7,7 @@ #include #endif -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/TreeViewModel/mainwindow.hpp b/TreeViewModel/mainwindow.hpp index 51b84cf..f0b50e9 100644 --- a/TreeViewModel/mainwindow.hpp +++ b/TreeViewModel/mainwindow.hpp @@ -13,11 +13,11 @@ class MainWindow : public QMainWindow Q_OBJECT public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event) override; private: class MainWindowPrivate; diff --git a/TreeViewModel/normaltreeview.cc b/TreeViewModel/normaltreeview.cc index 305499c..d294bc1 100644 --- a/TreeViewModel/normaltreeview.cc +++ b/TreeViewModel/normaltreeview.cc @@ -26,12 +26,13 @@ void NormalTreeModel::setDatas(const QFileInfoList &fileInfos, bool depth) emit layoutChanged(); } -int NormalTreeModel::rowCount(const QModelIndex &idx) const +auto NormalTreeModel::rowCount(const QModelIndex &idx) const -> int { return BaseTreeModel::rowCount(idx); } -QVariant NormalTreeModel::headerData(int section, Qt::Orientation orientation, int role) const +auto NormalTreeModel::headerData(int section, Qt::Orientation orientation, int role) const + -> QVariant { switch (role) { case Qt::TextAlignmentRole: return Qt::AlignVCenter; @@ -51,13 +52,13 @@ QVariant NormalTreeModel::headerData(int section, Qt::Orientation orientation, i } break; default: break; } - return QVariant(); + return {}; } class NormalTreeView::NormalTreeViewPrivate { public: - NormalTreeViewPrivate(QWidget *parent) + explicit NormalTreeViewPrivate(QWidget *parent) : owner(parent) , model(new NormalTreeModel(owner)) {} @@ -74,7 +75,7 @@ NormalTreeView::NormalTreeView(QWidget *parent) setupUI(); } -NormalTreeView::~NormalTreeView() {} +NormalTreeView::~NormalTreeView() = default; void NormalTreeView::setDatas(const QFileInfoList &fileInfos) { diff --git a/TreeViewModel/normaltreeview.hpp b/TreeViewModel/normaltreeview.hpp index f3a66b7..58a65a6 100644 --- a/TreeViewModel/normaltreeview.hpp +++ b/TreeViewModel/normaltreeview.hpp @@ -16,11 +16,15 @@ class NormalTreeModel : public BaseTreeModel void setDatas(const QFileInfoList &fileInfos, bool depth = false); - int rowCount(const QModelIndex &idx = QModelIndex()) const override; + [[nodiscard]] auto rowCount(const QModelIndex &idx = QModelIndex()) const -> int override; protected: - int columnCount(const QModelIndex &idx) const override { return m_headerList.size(); } - QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + [[nodiscard]] auto columnCount(const QModelIndex &idx) const -> int override + { + return m_headerList.size(); + } + [[nodiscard]] auto headerData(int section, Qt::Orientation orientation, int role) const + -> QVariant override; private: QStringList m_headerList; @@ -31,7 +35,7 @@ class NormalTreeView : public TreeView Q_OBJECT public: explicit NormalTreeView(QWidget *parent = nullptr); - ~NormalTreeView(); + ~NormalTreeView() override; void setDatas(const QFileInfoList &fileInfos); diff --git a/TreeViewModel/treemodel.cc b/TreeViewModel/treemodel.cc index 6aab15e..da0c10b 100644 --- a/TreeViewModel/treemodel.cc +++ b/TreeViewModel/treemodel.cc @@ -20,26 +20,26 @@ TreeItem::~TreeItem() removeChildren(); } -TreeItem *TreeItem::childAt(int pos) const +auto TreeItem::childAt(int pos) const -> TreeItem * { QTC_ASSERT(pos >= 0, return nullptr); return pos < childCount() ? *(begin() + pos) : nullptr; } -int TreeItem::indexOf(const TreeItem *item) const +auto TreeItem::indexOf(const TreeItem *item) const -> int { auto it = std::find(begin(), end(), item); return it == end() ? -1 : it - begin(); } -QVariant TreeItem::data(int column, int role) const +auto TreeItem::data(int column, int role) const -> QVariant { Q_UNUSED(column) Q_UNUSED(role) - return QVariant(); + return {}; } -bool TreeItem::setData(int column, const QVariant &data, int role) +auto TreeItem::setData(int column, const QVariant &data, int role) -> bool { Q_UNUSED(column) Q_UNUSED(data) @@ -47,18 +47,18 @@ bool TreeItem::setData(int column, const QVariant &data, int role) return false; } -Qt::ItemFlags TreeItem::flags(int column) const +auto TreeItem::flags(int column) const -> Qt::ItemFlags { Q_UNUSED(column) return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } -bool TreeItem::hasChildren() const +auto TreeItem::hasChildren() const -> bool { return canFetchMore() || childCount() > 0; } -bool TreeItem::canFetchMore() const +auto TreeItem::canFetchMore() const -> bool { return false; } @@ -177,17 +177,17 @@ void TreeItem::updateColumn(int column) } } -TreeItem *TreeItem::firstChild() const +auto TreeItem::firstChild() const -> TreeItem * { return childCount() == 0 ? nullptr : *begin(); } -TreeItem *TreeItem::lastChild() const +auto TreeItem::lastChild() const -> TreeItem * { return childCount() == 0 ? nullptr : *(end() - 1); } -int TreeItem::level() const +auto TreeItem::level() const -> int { int l = 0; for (TreeItem *item = this->parent(); item; item = item->parent()) @@ -195,18 +195,18 @@ int TreeItem::level() const return l; } -int TreeItem::indexInParent() const +auto TreeItem::indexInParent() const -> int { return m_parent ? m_parent->indexOf(this) : -1; } -QModelIndex TreeItem::index() const +auto TreeItem::index() const -> QModelIndex { QTC_ASSERT(m_model, return QModelIndex()); return m_model->indexForItem(this); } -QAbstractItemModel *TreeItem::model() const +auto TreeItem::model() const -> QAbstractItemModel * { return m_model; } @@ -239,7 +239,7 @@ void TreeItem::forChildrenAtLevel(int level, const std::function &pred) const +auto TreeItem::findChildAtLevel(int level, const std::function &pred) const -> TreeItem * { QTC_ASSERT(level > 0, return nullptr); if (level == 1) { @@ -255,7 +255,7 @@ TreeItem *TreeItem::findChildAtLevel(int level, const std::function &pred) const +auto TreeItem::findAnyChild(const std::function &pred) const -> TreeItem * { for (TreeItem *item : *this) { if (pred(item)) @@ -266,7 +266,7 @@ TreeItem *TreeItem::findAnyChild(const std::function &pred) co return nullptr; } -TreeItem *TreeItem::reverseFindAnyChild(const std::function &pred) const +auto TreeItem::reverseFindAnyChild(const std::function &pred) const -> TreeItem * { auto end = m_children.rend(); for (auto it = m_children.rbegin(); it != end; ++it) { @@ -355,28 +355,28 @@ BaseTreeModel::~BaseTreeModel() delete m_root; } -QModelIndex BaseTreeModel::parent(const QModelIndex &idx) const +auto BaseTreeModel::parent(const QModelIndex &idx) const -> QModelIndex { CHECK_INDEX(idx); if (!idx.isValid()) - return QModelIndex(); + return {}; const TreeItem *item = itemForIndex(idx); QTC_ASSERT(item, return QModelIndex()); TreeItem *parent = item->parent(); if (!parent || parent == m_root) - return QModelIndex(); + return {}; const TreeItem *grandparent = parent->parent(); if (!grandparent) - return QModelIndex(); + return {}; // This is on the performance-critical path for ItemViewFind. const int i = grandparent->m_children.indexOf(parent); return createIndex(i, 0, static_cast(parent)); } -QModelIndex BaseTreeModel::sibling(int row, int column, const QModelIndex &idx) const +auto BaseTreeModel::sibling(int row, int column, const QModelIndex &idx) const -> QModelIndex { const TreeItem *item = itemForIndex(idx); QTC_ASSERT(item, return QModelIndex()); @@ -388,7 +388,7 @@ QModelIndex BaseTreeModel::sibling(int row, int column, const QModelIndex &idx) return result; } -int BaseTreeModel::rowCount(const QModelIndex &idx) const +auto BaseTreeModel::rowCount(const QModelIndex &idx) const -> int { CHECK_INDEX(idx); if (!idx.isValid()) @@ -399,7 +399,7 @@ int BaseTreeModel::rowCount(const QModelIndex &idx) const return item ? item->childCount() : 0; } -int BaseTreeModel::columnCount(const QModelIndex &idx) const +auto BaseTreeModel::columnCount(const QModelIndex &idx) const -> int { CHECK_INDEX(idx); if (idx.column() > 0) @@ -407,7 +407,7 @@ int BaseTreeModel::columnCount(const QModelIndex &idx) const return m_columnCount; } -bool BaseTreeModel::setData(const QModelIndex &idx, const QVariant &data, int role) +auto BaseTreeModel::setData(const QModelIndex &idx, const QVariant &data, int role) -> bool { TreeItem *item = itemForIndex(idx); bool res = item ? item->setData(idx.column(), data, role) : false; @@ -417,22 +417,22 @@ bool BaseTreeModel::setData(const QModelIndex &idx, const QVariant &data, int ro return res; } -QVariant BaseTreeModel::data(const QModelIndex &idx, int role) const +auto BaseTreeModel::data(const QModelIndex &idx, int role) const -> QVariant { TreeItem *item = itemForIndex(idx); return item ? item->data(idx.column(), role) : QVariant(); } -QVariant BaseTreeModel::headerData(int section, Qt::Orientation orientation, int role) const +auto BaseTreeModel::headerData(int section, Qt::Orientation orientation, int role) const -> QVariant { if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section < m_header.size()) return m_header.at(section); if (role == Qt::ToolTipRole && section < m_headerToolTip.size()) return m_headerToolTip.at(section); - return QVariant(); + return {}; } -bool BaseTreeModel::hasChildren(const QModelIndex &idx) const +auto BaseTreeModel::hasChildren(const QModelIndex &idx) const -> bool { if (idx.column() > 0) return false; @@ -440,7 +440,7 @@ bool BaseTreeModel::hasChildren(const QModelIndex &idx) const return !item || item->hasChildren(); } -Qt::ItemFlags BaseTreeModel::flags(const QModelIndex &idx) const +auto BaseTreeModel::flags(const QModelIndex &idx) const -> Qt::ItemFlags { if (!idx.isValid()) return {}; @@ -448,7 +448,7 @@ Qt::ItemFlags BaseTreeModel::flags(const QModelIndex &idx) const return item ? item->flags(idx.column()) : (Qt::ItemIsEnabled | Qt::ItemIsSelectable); } -bool BaseTreeModel::canFetchMore(const QModelIndex &idx) const +auto BaseTreeModel::canFetchMore(const QModelIndex &idx) const -> bool { if (!idx.isValid()) return false; @@ -465,7 +465,7 @@ void BaseTreeModel::fetchMore(const QModelIndex &idx) item->fetchMore(); } -TreeItem *BaseTreeModel::rootItem() const +auto BaseTreeModel::rootItem() const -> TreeItem * { return m_root; } @@ -504,20 +504,20 @@ void BaseTreeModel::setHeaderToolTip(const QStringList &tips) m_headerToolTip = tips; } -QModelIndex BaseTreeModel::index(int row, int column, const QModelIndex &parent) const +auto BaseTreeModel::index(int row, int column, const QModelIndex &parent) const -> QModelIndex { CHECK_INDEX(parent); if (!hasIndex(row, column, parent)) - return QModelIndex(); + return {}; TreeItem *item = itemForIndex(parent); QTC_ASSERT(item, return QModelIndex()); if (row >= item->childCount()) - return QModelIndex(); + return {}; return createIndex(row, column, static_cast(item->childAt(row))); } -TreeItem *BaseTreeModel::itemForIndex(const QModelIndex &idx) const +auto BaseTreeModel::itemForIndex(const QModelIndex &idx) const -> TreeItem * { CHECK_INDEX(idx); TreeItem *item = idx.isValid() ? static_cast(idx.internalPointer()) : m_root; @@ -526,11 +526,11 @@ TreeItem *BaseTreeModel::itemForIndex(const QModelIndex &idx) const return item; } -QModelIndex BaseTreeModel::indexForItem(const TreeItem *item) const +auto BaseTreeModel::indexForItem(const TreeItem *item) const -> QModelIndex { QTC_ASSERT(item, return QModelIndex()); if (item == m_root) - return QModelIndex(); + return {}; TreeItem *p = item->parent(); QTC_ASSERT(p, return QModelIndex()); @@ -555,7 +555,7 @@ void BaseTreeModel::clear() \note The item is not destroyed, ownership is effectively passed to the caller. */ -TreeItem *BaseTreeModel::takeItem(TreeItem *item) +auto BaseTreeModel::takeItem(TreeItem *item) -> TreeItem * { #if USE_MODEL_TEST (void) new ModelTest(this, this); diff --git a/TreeViewModel/treemodel.hpp b/TreeViewModel/treemodel.hpp index 81946b0..4836f76 100644 --- a/TreeViewModel/treemodel.hpp +++ b/TreeViewModel/treemodel.hpp @@ -43,15 +43,15 @@ class TreeItem TreeItem(); virtual ~TreeItem(); - virtual QVariant data(int column, int role) const; - virtual bool setData(int column, const QVariant &data, int role); - virtual Qt::ItemFlags flags(int column) const; + [[nodiscard]] virtual auto data(int column, int role) const -> QVariant; + virtual auto setData(int column, const QVariant &data, int role) -> bool; + [[nodiscard]] virtual Qt::ItemFlags flags(int column) const; - virtual bool hasChildren() const; - virtual bool canFetchMore() const; + [[nodiscard]] virtual auto hasChildren() const -> bool; + [[nodiscard]] virtual auto canFetchMore() const -> bool; virtual void fetchMore() {} - TreeItem *parent() const { return m_parent; } + [[nodiscard]] auto parent() const -> TreeItem * { return m_parent; } void prependChild(TreeItem *item); void appendChild(TreeItem *item); @@ -67,31 +67,34 @@ class TreeItem void updateColumn(int column); void expand(); void collapse(); - TreeItem *firstChild() const; - TreeItem *lastChild() const; - int level() const; + [[nodiscard]] auto firstChild() const -> TreeItem *; + [[nodiscard]] auto lastChild() const -> TreeItem *; + [[nodiscard]] auto level() const -> int; using const_iterator = QVector::const_iterator; using value_type = TreeItem *; - int childCount() const { return m_children.size(); } - int indexInParent() const; - TreeItem *childAt(int index) const; - int indexOf(const TreeItem *item) const; - const_iterator begin() const { return m_children.begin(); } - const_iterator end() const { return m_children.end(); } - QModelIndex index() const; - QAbstractItemModel *model() const; + [[nodiscard]] auto childCount() const -> int { return m_children.size(); } + [[nodiscard]] auto indexInParent() const -> int; + [[nodiscard]] auto childAt(int index) const -> TreeItem *; + auto indexOf(const TreeItem *item) const -> int; + [[nodiscard]] const_iterator begin() const { return m_children.begin(); } + [[nodiscard]] const_iterator end() const { return m_children.end(); } + [[nodiscard]] auto index() const -> QModelIndex; + [[nodiscard]] auto model() const -> QAbstractItemModel *; void forSelectedChildren(const std::function &pred) const; void forAllChildren(const std::function &pred) const; - TreeItem *findAnyChild(const std::function &pred) const; + [[nodiscard]] auto findAnyChild(const std::function &pred) const + -> TreeItem *; // like findAnyChild() but processes children in exact reverse order // (bottom to top, most inner children first) - TreeItem *reverseFindAnyChild(const std::function &pred) const; + [[nodiscard]] auto reverseFindAnyChild(const std::function &pred) const + -> TreeItem *; // Levels are 1-based: Child at Level 1 is an immediate child. void forChildrenAtLevel(int level, const std::function &pred) const; - TreeItem *findChildAtLevel(int level, const std::function &pred) const; + [[nodiscard]] auto findChildAtLevel(int level, const std::function &pred) const + -> TreeItem *; private: TreeItem(const TreeItem &) = delete; @@ -122,28 +125,31 @@ class BaseTreeModel : public QAbstractItemModel void setHeaderToolTip(const QStringList &tips); void clear(); - TreeItem *rootItem() const; + [[nodiscard]] auto rootItem() const -> TreeItem *; void setRootItem(TreeItem *item); - TreeItem *itemForIndex(const QModelIndex &) const; - QModelIndex indexForItem(const TreeItem *needle) const; - - int rowCount(const QModelIndex &idx = QModelIndex()) const override; - int columnCount(const QModelIndex &idx) const override; - - bool setData(const QModelIndex &idx, const QVariant &data, int role) override; - QVariant data(const QModelIndex &idx, int role) const override; - QModelIndex index(int, int, const QModelIndex &idx = QModelIndex()) const override; - QModelIndex parent(const QModelIndex &idx) const override; - QModelIndex sibling(int row, int column, const QModelIndex &idx) const override; - Qt::ItemFlags flags(const QModelIndex &idx) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - bool hasChildren(const QModelIndex &idx) const override; - - bool canFetchMore(const QModelIndex &idx) const override; + [[nodiscard]] auto itemForIndex(const QModelIndex &) const -> TreeItem *; + auto indexForItem(const TreeItem *needle) const -> QModelIndex; + + [[nodiscard]] auto rowCount(const QModelIndex &idx = QModelIndex()) const -> int override; + [[nodiscard]] auto columnCount(const QModelIndex &idx) const -> int override; + + auto setData(const QModelIndex &idx, const QVariant &data, int role) -> bool override; + [[nodiscard]] auto data(const QModelIndex &idx, int role) const -> QVariant override; + [[nodiscard]] auto index(int, int, const QModelIndex &idx = QModelIndex()) const + -> QModelIndex override; + [[nodiscard]] auto parent(const QModelIndex &idx) const -> QModelIndex override; + [[nodiscard]] auto sibling(int row, int column, const QModelIndex &idx) const + -> QModelIndex override; + [[nodiscard]] Qt::ItemFlags flags(const QModelIndex &idx) const override; + [[nodiscard]] auto headerData(int section, Qt::Orientation orientation, int role) const + -> QVariant override; + [[nodiscard]] auto hasChildren(const QModelIndex &idx) const -> bool override; + + [[nodiscard]] auto canFetchMore(const QModelIndex &idx) const -> bool override; void fetchMore(const QModelIndex &idx) override; - TreeItem *takeItem(TreeItem *item); // item is not destroyed. - void destroyItem(TreeItem *item); // item is destroyed. + auto takeItem(TreeItem *item) -> TreeItem *; // item is not destroyed. + void destroyItem(TreeItem *item); // item is destroyed. signals: void requestExpansion(const QModelIndex &); diff --git a/TreeViewModel/treeview.cc b/TreeViewModel/treeview.cc index 5f7a2a9..8d09f2f 100644 --- a/TreeViewModel/treeview.cc +++ b/TreeViewModel/treeview.cc @@ -12,7 +12,7 @@ TreeView::TreeView(QWidget *parent) buildConnect(); } -QModelIndexList TreeView::selectedIndexes() const +auto TreeView::selectedIndexes() const -> QModelIndexList { QModelIndexList indexList(QTreeView::selectedIndexes()); QModelIndexList list; @@ -26,7 +26,7 @@ QModelIndexList TreeView::selectedIndexes() const return list; } -QModelIndexList TreeView::allIndexes() const +auto TreeView::allIndexes() const -> QModelIndexList { QModelIndexList list; QAbstractItemModel *model = this->model(); @@ -39,7 +39,7 @@ QModelIndexList TreeView::allIndexes() const return list; } -int TreeView::pageSize() +auto TreeView::pageSize() -> int { m_pageSize = height() / 50 + 2; return m_pageSize; diff --git a/TreeViewModel/treeview.hpp b/TreeViewModel/treeview.hpp index 7c0d8cc..f1075b1 100644 --- a/TreeViewModel/treeview.hpp +++ b/TreeViewModel/treeview.hpp @@ -9,11 +9,11 @@ class TreeView : public QTreeView public: explicit TreeView(QWidget *parent = nullptr); - QModelIndexList selectedIndexes() const; + [[nodiscard]] auto selectedIndexes() const -> QModelIndexList override; - QModelIndexList allIndexes() const; + [[nodiscard]] auto allIndexes() const -> QModelIndexList; - virtual int pageSize(); + virtual auto pageSize() -> int; signals: void selectedChanged(); @@ -27,7 +27,7 @@ private slots: void onFetchMore(int value); protected: - void showEvent(QShowEvent *event); + void showEvent(QShowEvent *event) override; protected: int m_pageSize = 20; diff --git a/Validator/main.cc b/Validator/main.cc index e9bbf59..5d48a9d 100644 --- a/Validator/main.cc +++ b/Validator/main.cc @@ -7,7 +7,7 @@ #include #endif -int main(int argc, char *argv[]) +auto main(int argc, char *argv[]) -> int { QApplication a(argc, argv); MainWindow w; diff --git a/Validator/mainwindow.hpp b/Validator/mainwindow.hpp index 2a84cf2..971b4a4 100644 --- a/Validator/mainwindow.hpp +++ b/Validator/mainwindow.hpp @@ -1,19 +1,14 @@ #ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP -#include -#if QT_VERSION >= 0x050000 -#include -#else -#include -#endif +#include class MainWindow : public QMainWindow { Q_OBJECT - - public: - MainWindow(QWidget *parent = nullptr); - ~MainWindow(); +public: + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; }; + #endif // MAINWINDOW_HPP diff --git a/Validator/validator.cc b/Validator/validator.cc index 126c01e..7999438 100644 --- a/Validator/validator.cc +++ b/Validator/validator.cc @@ -1,6 +1,6 @@ #include "validator.hpp" -QValidator::State IntValidator::validate(QString &input, int &pos) const +auto IntValidator::validate(QString &input, int &pos) const -> QValidator::State { const State originalRes = QIntValidator::validate(input, pos); if (originalRes != Intermediate || input.isEmpty()) { @@ -18,7 +18,7 @@ QValidator::State IntValidator::validate(QString &input, int &pos) const return originalRes; } -QValidator::State DoubleValidator::validate(QString &input, int &pos) const +auto DoubleValidator::validate(QString &input, int &pos) const -> QValidator::State { const State originalRes = QDoubleValidator::validate(input, pos); if (originalRes != Intermediate || input.isEmpty()) { diff --git a/Validator/validator.hpp b/Validator/validator.hpp index 6e08114..d8dedd9 100644 --- a/Validator/validator.hpp +++ b/Validator/validator.hpp @@ -9,7 +9,7 @@ class IntValidator : public QIntValidator public: using QIntValidator::QIntValidator; - State validate(QString &input, int &pos) const override; + auto validate(QString &input, int &pos) const -> State override; }; class DoubleValidator : public QDoubleValidator @@ -18,7 +18,7 @@ class DoubleValidator : public QDoubleValidator public: using QDoubleValidator::QDoubleValidator; - State validate(QString &input, int &pos) const override; + auto validate(QString &input, int &pos) const -> State override; }; #endif // VALIDATOR_HPP