qformatter.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #ifndef QFORMATTER_H
  2. #define QFORMATTER_H
  3. #include <fmt/chrono.h>
  4. #include <fmt/format.h>
  5. #include <fmt/ranges.h>
  6. #include <QByteArray>
  7. #include <QColor>
  8. #include <QDate>
  9. #include <QProcess>
  10. #include <QString>
  11. #include <QTextCodec>
  12. namespace fmt {
  13. template<>
  14. struct formatter<QString>
  15. {
  16. constexpr auto parse(format_parse_context& ctx)
  17. {
  18. auto it = ctx.begin();
  19. if (it != ctx.end() && *it == '}')
  20. it++;
  21. return it;
  22. }
  23. template<typename Context>
  24. auto format(const QString& str, Context& ctx) const
  25. {
  26. QTextCodec* codec = QTextCodec::codecForName("GBK"); // 日文编码
  27. if (codec) {
  28. QByteArray bytes = codec->fromUnicode(str);
  29. return fmt::format_to(ctx.out(), "{}", bytes);
  30. }
  31. return fmt::format_to(ctx.out(), "{}", str.toUtf8());
  32. }
  33. };
  34. template<>
  35. struct formatter<QByteArray> : formatter<std::string>
  36. {
  37. template<typename FormatContext>
  38. auto format(const QByteArray& a, FormatContext& ctx) const
  39. {
  40. return format_to(ctx.out(), "{}", a.constData());
  41. }
  42. };
  43. template<>
  44. struct fmt::formatter<QDate> : fmt::formatter<std::string>
  45. {
  46. static auto format(const QDate& t, fmt::format_context& ctx)
  47. {
  48. return fmt::format_to(ctx.out(), "{}", t.toString(Qt::ISODate));
  49. }
  50. };
  51. template<>
  52. struct fmt::formatter<QTime> : fmt::formatter<std::string>
  53. {
  54. static auto format(const QTime& t, fmt::format_context& ctx)
  55. {
  56. return fmt::format_to(ctx.out(), "{}", t.toString(Qt::ISODate));
  57. }
  58. };
  59. template<>
  60. struct fmt::formatter<QDateTime> : fmt::formatter<std::string>
  61. {
  62. static auto format(const QDateTime& t, fmt::format_context& ctx)
  63. {
  64. return fmt::format_to(ctx.out(), "{}", t.toString(Qt::ISODate));
  65. }
  66. };
  67. template<>
  68. struct fmt::formatter<QPoint> : fmt::formatter<std::string>
  69. {
  70. static auto format(const QPoint& p, fmt::format_context& ctx)
  71. {
  72. return fmt::format_to(ctx.out(), "[{}, {}]", p.x(), p.y());
  73. }
  74. };
  75. template<>
  76. struct fmt::formatter<QPointF> : fmt::formatter<std::string>
  77. {
  78. static auto format(const QPointF& p, fmt::format_context& ctx)
  79. {
  80. return fmt::format_to(ctx.out(), "[{}, {}]", p.x(), p.y());
  81. }
  82. };
  83. template<>
  84. struct fmt::formatter<QColor> : fmt::formatter<std::string>
  85. {
  86. static auto format(const QColor& c, fmt::format_context& ctx)
  87. {
  88. return fmt::format_to(ctx.out(), "{}", c.name());
  89. }
  90. };
  91. } // namespace fmt
  92. #endif // QFORMATTER_H