文章首發地址:
要輸出彩色信息有點類似於html的語法,即在要輸出的文字前加上一段顏色指令。
指令格式如下 33[*m 這裡的*就是轉義字元,例如我們要輸出一段綠色的文字,則
qDebug() << " 33[32m" <<"Hello!";
即在輸出文字前,先輸出一個顏色指令。 注意這個指令對後續的輸出都會生效,
如果想關掉顏色只要再輸出0號指令即可
qDebug() << " 33[0m";
這裡有一個指令表
0 : Reset Color Attributes 1 : 加粗 2 : 去粗 4 : 下劃線 5 : 閃爍 7 : 反色 21/22 : 加粗 正常 24 : 去掉下劃線 25 : 停止閃爍 27 : 反色 30 : 前景,黑色 31 : 前景,紅色 32 : 前景,綠色 33 : 前景,黃色 34 : 前景,籃色 35 : 前景,紫色 36 : 前景,青色 37 : 前景,白色 40 : 背景,黑色 41 : 背景,紅色 42 : 背景,綠色 43 : 背景,黃色 44 : 背景,籃色 45 : 背景,紫色 46 : 背景,青色 47 : 背景,白色 其它轉義字元命令 清除屏幕 : /033c 設定水平標位置 : /033[XG X為水平標位置。 設定垂直標位置 : /033[Xd Y為垂直標位置。 /033[0K : 刪除從標到該行結尾 /033[1K : 刪除從該行開始到標處 /033[2K : 刪除整行 /033[0J : 刪除標到螢幕結尾 /033[1J : 刪除從螢幕開始到標處 /033[2J : 刪除整個屏幕
(代碼使用C++11標準)
enum class LogType { Reset = 0,
Bold, Unbold,
FrontBlack, FrontRed, FrontGreen, FrontYellow, FrontBlue, FrontPurple, FrontCyan, FrontWhite, BackBlack, BackRed, BackGreen, BackYellow, BackBlue, BackPurple, BackCyan, BackWhite,
TypeCount };
static const char * logCommands[] = { " 33[0m", " 33[1m", " 33[2m", " 33[30m", " 33[31m", " 33[32m", " 33[33m", " 33[34m", " 33[35m", " 33[36m", " 33[37m", " 33[40m", " 33[41m", " 33[42m", " 33[43m", " 33[44m", " 33[45m", " 33[46m", " 33[47m", };
logCommands[(int)(LogType::FrontYellow)]
template <typename EnumType, typename IntType = int> int enumToInt(EnumType enumValue) { static_assert (std::is_enum<EnumType>::value, "EnumType must be enum");
return static_cast<IntType>(enumValue); }
#include <QDebug> enum class LogType { Reset = 0,
TypeCount }; static const char * logCommands[] = { " 33[0m", " 33[1m", " 33[2m", " 33[30m", " 33[31m", " 33[32m", " 33[33m", " 33[34m", " 33[35m", " 33[36m", " 33[37m", " 33[40m", " 33[41m", " 33[42m", " 33[43m", " 33[44m", " 33[45m", " 33[46m", " 33[47m", }; template <typename EnumType, typename IntType = int> int enumToInt(EnumType enumValue) { static_assert (std::is_enum<EnumType>::value, "EnumType must be enum");
return static_cast<IntType>(enumValue); } int main(int argc, char *argv[]) { for (int i = enumToInt(LogType::Bold); i < enumToInt(LogType::TypeCount); ++i) { qInfo().nospace() << logCommands[i] << i << " Hello World" << logCommands[0]; } qWarning() << logCommands[enumToInt(LogType::FrontBlue)] << logCommands[enumToInt(LogType::BackRed)] << u8"感謝大家對濤哥系列文章的支持,也" "歡迎直接聯繫我尋求幫助" << logCommands[0]; return 0; }
推薦閱讀: