*本项目的Readme.md大部分由AI生成,仅作者在必要部分加以修改(如注意事项部分) *
The majority of this project's Readme.md is generated by AI, with only necessary modifications made by the author (such as the notes section)
本项目是一个基于Qt框架的轻量级控制台组件,旨在为Qt Widget应用程序提供类似Shell的交互式控制台界面。它支持命令输入、自定义命令处理、样式配置和缓冲区流输出,适用于需要嵌入控制台功能的场景(如调试工具、脚本运行器、终端模拟器等)。
- Shell模式交互
- 模拟终端的输入输出方式,自动添加提示符(
>
)。 - 防止光标移动到提示符前(通过事件过滤器实现)。
- 回车键发送命令,自动滚动到最新内容。
- 灵活的命令处理
- 静态命令:命令与字符串响应关联(如
"hello"
→"Hello, World!"
)。 - 动态命令:命令与函数关联(如
"test"
→ 执行自定义逻辑)。
- 可配置的样式
- 通过
Config
类自定义背景颜色、文本颜色、字体大小和欢迎消息。 - 支持动态刷新样式(
refreshAllStyleSheet
)。
- 缓冲区流输出
- 支持链式输出(如
*console << "hello" << 123 << QString("Qt")
)。 - 自动处理不同类型数据(字符串、数值、
QString
等)。
- 自动滚动
- 输出内容时,控制台将自动滚动到底部。
- Qt:Qt5或更高版本(需包含
Widgets
模块)。 - C++编译器:须>=C++17(如GCC 8+、Clang 6+、MSVC 2019+)。
- 构建工具:CMake 3.16或更高版本(推荐)。
- 克隆仓库
git clone https://github.com/CCA8798/ConsoleInQt.git
cd ConsoleInQt
- 创建构建目录
mkdir build && cd build
- 运行CMake
cmake .. -DCMAKE_PREFIX_PATH=/path/to/qt -DCMAKE_BUILD_TYPE=Release
(替换 /path/to/qt
为你的Qt安装路径,如 C:/Qt/5.15.2/mingw81_64
)。
- 编译项目
cmake --build . --target ConsoleInQt --config Release
- 添加头文件和库
将
Console.h
和Console.cpp
添加到你的项目中,并链接Qt的Widgets
模块:
# CMakeLists.txt
find_package(Qt5 COMPONENTS Widgets REQUIRED)
target_link_libraries(YourProject Qt5::Widgets ConsoleInQt)
- 使用Console组件
在
MainWindow
中创建Console
对象,插入命令并配置样式:
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <Console.h>
using namespace ConsoleInQt;
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget* parent = nullptr) : QMainWindow(parent) {
// 创建Console对象
Console* console = new Console(this);
console->resize(this->size());
// 插入静态命令:"hello" → "Hello, World!"
console->insertCommand("hello", "Hello, World!");
// 插入动态命令:"test" → 输出1-10
console->insertCommand("test", [console]() {
for (int i = 1; i <= 10; i++) {
*console << "Test output: " << i << "\n";
}
});
// 配置欢迎消息和样式
Config config;
config.setWelcomeMessage("Welcome to ConsoleInQt!");
config.setBackgroundColor("black");
config.setTextColor("white");
config.setTextSize("20");
console->refreshAllStyleSheet(config);
}
};
#endif // MAINWINDOW_H
Config
类用于管理控制台的样式和行为,常用方法如下:
方法 | 描述 | 默认值 |
---|---|---|
setWelcomeMessage |
设置欢迎消息 | 空字符串 |
setBackgroundColor |
设置背景颜色 | "black" |
setTextColor |
设置文本颜色 | "white" |
setTextSize |
设置字体大小(px) | "20" |
getCurrentConfig |
获取当前配置(生成样式表) | - |
描述:继承自 QObject
,用于管理控制台的样式(如背景色、文本色)和行为(如欢迎消息)。
方法签名 | 描述 |
---|---|
void setWelcomeMessage(const QString& WelcomeMessageSc) |
设置欢迎消息(启动时显示) |
void setBackgroundColor(const QString& BackgroundColorSc) |
设置控制台背景颜色 |
void setTextColor(const QString& TextColorSc) |
设置控制台文本颜色 |
void setTextSize(const QString& TextSizeSc) |
设置文本字体大小(单位:px) |
方法签名 | 描述 |
---|---|
QString getWelcomeMessage(void) const |
获取当前欢迎消息 |
QString getBackgroundColor(void) const |
获取当前背景颜色 |
QString getTextColor(void) const |
获取当前文本颜色 |
QString getTextSize(void) const |
获取当前字体大小 |
size_t TestingOutput() const |
测试接口,返回控制台模式(固定为 Shell 模式) |
QString getCurrentConfig(void) const |
生成当前配置的样式表字符串(用于设置控件样式) |
描述:辅助类,用于暂存输出数据,析构时批量处理并输出到控制台。
方法签名 | 描述 |
---|---|
explicit ConsoleBufferStream(Console& console) |
关联到指定的 Console 对象,初始化输出缓冲区 |
方法签名 | 描述 |
---|---|
template<typename BufferT = std::string_view> ConsoleBufferStream& operator<<(const BufferT& data) |
模板化输出运算符,支持以下类型:<br> - 字符串(std::string 、const char* 、QString )<br> - 数值(int 、float 等算术类型)<br> - 其他可转换为字符串的类型(通过 std::stringstream 处理) |
方法签名 | 描述 |
---|---|
~ConsoleBufferStream() |
析构时将缓冲区数据传递给 Console 对象处理(调用 console.processBuffer(buffer) ) |
描述:继承自 QWidget
,实现交互式控制台界面(如命令输入、自动滚动)和逻辑(如命令处理)。
信号签名 | 描述 |
---|---|
void commandSend(const QString& command) |
当用户输入命令并按回车键时发射,传递去除提示符(> )后的命令字符串(如用户输入 >test ,则传递 test )(一定要看注意事项!!!) |
方法签名 | 描述 |
---|---|
explicit Console(QWidget* parent = nullptr, const Config& defaultConfig = Config(), const QSize& defaultSize = QSize()) |
构造函数:<br> - parent :父控件(默认 nullptr )<br> - defaultConfig :初始配置(默认使用 Config 类的默认值)<br> - defaultSize :初始大小(默认自适应父控件) |
~Console() override |
析构函数,释放控件资源 |
bool getProcessing() const |
返回当前是否在处理命令(isProcessing 的状态,true 表示正在处理) |
void setProcess(const bool& newValue) |
设置是否在处理命令(isProcessing ) |
void insertCommand(const QString& command, const QString& response) |
添加静态命令(命令→字符串响应,如 insertCommand("hello", "Hello World!") ) |
void insertCommand(const char* command, const char* response) |
添加静态命令(char* 版本) |
void insertCommand(const char* command, std::function<void()> response) |
添加动态命令(命令→函数响应,如 insertCommand("test", [](){ /* 执行自定义逻辑 */ }) ) |
template<typename OutputT = std::string_view> ConsoleBufferStream operator<<(OutputT&& content) |
重载输出运算符,创建 ConsoleBufferStream 对象,支持链式输出(如 *console << "hello" << 123 << QString("Qt") ) |
void refreshAllStyleSheet(const Config& config) |
刷新所有控件的样式表(应用新配置) |
变量名 | 类型 | 描述 |
---|---|---|
startProcessing |
std::function<void()> |
函数对象:设置 isProcessing = true (标记为正在处理命令) |
stopProcessing |
std::function<void()> |
函数对象:设置 isProcessing = false (标记为停止处理命令) |
// 创建控制台对象
Console* console = new Console(this);
// 添加静态命令("hello" → "Hello World!")
console->insertCommand("hello", "Hello World!");
// 添加动态命令("test" → 输出 1-10)
console->insertCommand("test", [console]() {
for (int i = 1; i <= 10; i++) {
*console << "Test output: " << i << "\n";
}
});
// 配置样式
Config config;
config.setWelcomeMessage("Welcome to ConsoleInQt!");
config.setBackgroundColor("black");
config.setTextColor("white");
config.setTextSize("20");
console->refreshAllStyleSheet(config);
- 本库在输出部分引入了QTimer::singleShot,故请在耗时操作(如大量输出)时引入QCoreApplication::processEvents(),否则有极大概率会爆句柄。
- 本库代码部分注释不全。
- UI 线程安全:所有 UI 操作(如创建
QLineEdit
、设置样式)均在主线程执行,避免跨线程调用。 - 命令处理:
- 静态命令:直接返回字符串响应(如
insertCommand("hello", "Hello World!")
)。 - 动态命令:执行自定义函数(如
insertCommand("test", [](){ /* 执行耗时操作 */ })
),需注意避免阻塞 UI 线程(建议使用QTimer
或QThread
异步处理)。 - 自定义命令接收(很重要):如有与commandSend相关的槽,并且该槽内有多行针对Console类的输出操作的话,请在槽函数开头执行startProcessing(),在槽函数末尾执行stopProcessing(),否则会有格式错乱的问题发生。
- 样式刷新:修改
Config
类的配置后,需调用Console::refreshAllStyleSheet(config)
才能应用新样式。
欢迎贡献代码!请尽量遵循以下规范:
- 代码风格:Google C++风格指南。
- 提交PR:fork仓库后,创建
feature
分支,提交前运行测试(如果有),并添加详细说明。 - 问题反馈:使用GitHub Issues提交问题,描述现象、重现步骤和环境(Qt版本、编译器、操作系统)。
本项目采用MIT License,详情请见LICENSE文件。
- 作者:LZC(目前13岁)
- GitHub:CCA8798
- 邮箱:2044187229@qq.com
This version is translated by AI. Please feel free to ask questions and make modifications.
This project is a lightweight console component based on the Qt framework, designed to provide a Shell-like interactive console interface for Qt Widget applications. It supports command input, custom command handling, style configuration, and buffer stream output, making it suitable for scenarios requiring embedded console functionality (e.g., debugging tools, script runners, terminal emulators).
- Shell Mode Interaction
- Emulates terminal input/output behavior and automatically adds a prompt (
>
). - Prevents the cursor from moving before the prompt (implemented via an event filter).
- Sends commands on Enter key press and automatically scrolls to the latest content.
- Flexible Command Handling
- Static Commands: Map commands to string responses (e.g.,
"hello"
→"Hello, World!"
). - Dynamic Commands: Map commands to function responses (e.g.,
"test"
→ execute custom logic).
- Configurable Styling
- Customize background color, text color, font size, and welcome messages via the
Config
class. - Support for dynamically refreshing styles (using
refreshAllStyleSheet
).
- Buffer Stream Output
- Chainable output (e.g.,
*console << "hello" << 123 << QString("Qt")
). - Automatic handling of various data types (strings, numbers,
QString
, etc.).
- Auto-Scrolling
- The console automatically scrolls to the bottom when new content is output.
- Qt: Qt5 or higher (requires the
Widgets
module). - C++ Compiler: C++17 or later (e.g., GCC 8+, Clang 6+, MSVC 2019+).
- Build Tool: CMake 3.16 or higher (recommended).
- Clone the Repository
git clone https://github.com/CCA8798/ConsoleInQt.git
cd ConsoleInQt
- Create a Build Directory
mkdir build && cd build
- Run CMake
cmake .. -DCMAKE_PREFIX_PATH=/path/to/qt -DCMAKE_BUILD_TYPE=Release
(Replace /path/to/qt
with your Qt installation path, e.g., C:/Qt/5.15.2/mingw81_64
.)
- Build the Project
cmake --build . --target ConsoleInQt --config Release
- Add Header Files and Libraries
Include
Console.h
andConsole.cpp
in your project, and link against Qt'sWidgets
module:
# CMakeLists.txt
find_package(Qt5 COMPONENTS Widgets REQUIRED)
target_link_libraries(YourProject Qt5::Widgets ConsoleInQt)
- Use the Console Component
Create a
Console
object in yourMainWindow
, insert commands, and configure styles:
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <Console.h>
using namespace ConsoleInQt;
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget* parent = nullptr) : QMainWindow(parent) {
// Create a Console object
Console* console = new Console(this);
console->resize(this->size());
// Insert a static command: "hello" → "Hello, World!"
console->insertCommand("hello", "Hello, World!");
// Insert a dynamic command: "test" → Output 1-10
console->insertCommand("test", [console]() {
for (int i = 1; i <= 10; i++) {
*console << "Test output: " << i << "\n";
}
});
// Configure welcome message and styles
Config config;
config.setWelcomeMessage("Welcome to ConsoleInQt!");
config.setBackgroundColor("black");
config.setTextColor("white");
config.setTextSize("20");
console->refreshAllStyleSheet(config);
}
};
#endif // MAINWINDOW_H
The Config
class manages console styling and behavior. Key methods are as follows:
Method | Description | Default Value |
---|---|---|
setWelcomeMessage |
Set the welcome message | Empty string |
setBackgroundColor |
Set the background color | "black" |
setTextColor |
Set the text color | "white" |
setTextSize |
Set the font size (px) | "20" |
getCurrentConfig |
Get current config (generates stylesheet) | - |
Description: Inherits from QObject
, used to manage console styles (e.g., background color, text color) and behavior (e.g., welcome message).
Method Signature | Description |
---|---|
void setWelcomeMessage(const QString& WelcomeMessageSc) |
Set the welcome message (displayed on startup) |
void setBackgroundColor(const QString& BackgroundColorSc) |
Set the console background color |
void setTextColor(const QString& TextColorSc) |
Set the console text color |
void setTextSize(const QString& TextSizeSc) |
Set the font size (in px) |
Method Signature | Description |
---|---|
QString getWelcomeMessage(void) const |
Get the current welcome message |
QString getBackgroundColor(void) const |
Get the current background color |
QString getTextColor(void) const |
Get the current text color |
QString getTextSize(void) const |
Get the current font size |
size_t TestingOutput() const |
Test interface, returns console mode (fixed to Shell mode) |
QString getCurrentConfig(void) const |
Generate stylesheet string for current config (used to set widget styles) |
Description: Auxiliary class used to temporarily store output data, which is processed and output to the console upon destruction.
Method Signature | Description |
---|---|
explicit ConsoleBufferStream(Console& console) |
Associate with a specified Console object and initialize the output buffer |
Method Signature | Description |
---|---|
template<typename BufferT = std::string_view> ConsoleBufferStream& operator<<(const BufferT& data) |
Template output operator, supporting:<br> - Strings (std::string , const char* , QString )<br> - Numbers (arithmetic types like int , float )<br> - Other types convertible to strings (processed via std::stringstream ) |
Method Signature | Description |
---|---|
~ConsoleBufferStream() |
Pass buffer data to the Console object for processing (calls console.processBuffer(buffer) ) upon destruction |
Description: Inherits from QWidget
, implements interactive console interface (e.g., command input, auto-scrolling) and logic (e.g., command handling).
Signal Signature | Description |
---|---|
void commandSend(const QString& command) |
Emitted when the user enters a command and presses Enter, passing thecommand string without the prompt (> ) (e.g., if the user enters >test , it passes test ) (PLEASE READ THE NOTES!!) |
Method Signature | Description |
---|---|
explicit Console(QWidget* parent = nullptr, const Config& defaultConfig = Config(), const QSize& defaultSize = QSize()) |
Constructor:<br> - parent : Parent widget (default nullptr )<br> - defaultConfig : Initial configuration (uses Config default values by default)<br> - defaultSize : Initial size (adapts to parent widget by default) |
~Console() override |
Destructor, releases widget resources |
bool getProcessing() const |
Returns whether a command is currently being processed (isProcessing state, true means processing) |
void setProcess(const bool& newValue) |
Sets whether a command is being processed (isProcessing ) |
void insertCommand(const QString& command, const QString& response) |
Adds astatic command (command → string response, e.g., insertCommand("hello", "Hello World!") ) |
void insertCommand(const char* command, const char* response) |
Adds a static command (char* version) |
void insertCommand(const char* command, std::function<void()> response) |
Adds adynamic command (command → function response, e.g., insertCommand("test", [](){ /* execute custom logic */ }) ) |
template<typename OutputT = std::string_view> ConsoleBufferStream operator<<(OutputT&& content) |
Overloaded output operator, creates a ConsoleBufferStream object, supporting chained output (e.g., *console << "hello" << 123 << QString("Qt") ) |
void refreshAllStyleSheet(const Config& config) |
Refreshes stylesheets for all widgets (applies new configuration) |
Variable Name | Type | Description |
---|---|---|
startProcessing |
std::function<void()> |
Function object: Sets isProcessing = true (marks as processing a command) |
stopProcessing |
std::function<void()> |
Function object: Sets isProcessing = false (marks as stopping processing) |
- This library uses
QTimer::singleShot
for output. For time-consuming operations (e.g., large-scale output), includeQCoreApplication::processEvents()
; otherwise, there is a high probability of handle exhaustion. - Some parts of the library code lack detailed comments.
- UI Thread Safety: All UI operations (e.g., creating
QLineEdit
, setting styles) are executed in the main thread (UI thread). Avoid cross-thread calls. - Command Handling:
- Static Commands: Directly return a string response (e.g.,
insertCommand("hello", "Hello World!")
). - Dynamic Commands: Execute custom functions (e.g.,
insertCommand("test", [](){ /* execute time-consuming operations */ })
). Note to avoid blocking the UI thread (recommend usingQTimer
orQThread
for asynchronous processing).
- Custom Command Receiving (Important): If you have slots related to
commandSend
and the slot contains multiple output operations for theConsole
class, please callstartProcessing()
at the beginning of the slot function andstopProcessing()
at the end. Otherwise, formatting issues may occur. - Style Refresh: After modifying the
Config
class configuration, callConsole::refreshAllStyleSheet(config)
to apply the new styles.
Contributions are welcome! Please follow these guidelines:
- Code Style: Adhere to the Google C++ Style Guide.
- PR Submissions: Fork the repository, create a
feature
branch, run tests (if any) before submitting, and add detailed descriptions. - Issue Reporting: Use GitHub Issues to report problems, including steps to reproduce, Qt version, compiler, and operating system.
This project is licensed under the MIT License. See the LICENSE file for details.
- Author: LZC (13 years old)
- GitHub: CCA8798
- Email: 2044187229@qq.com
Special thanks to the Qt community for providing an excellent framework, and to everyone who supported and encouraged this project!