2. 按钮点击事件处理

任务目标

创建一个Qt Widgets窗口,在窗口中放置一个按钮。点击按钮时,窗口背景颜色在预设的几种颜色之间循环切换,同时按钮文字实时显示当前背景色名称。

环境依赖

需要Qt 5或Qt 6开发环境,以及对应的C++编译器。本案例使用Qt Widgets模块,无需额外第三方库。

关键完整代码

// main.cpp
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QColor>

class ColorWindow : public QWidget {
public:
    ColorWindow() {
        // 初始化颜色列表
        colors = {QColor("#F0F0F0"), QColor("#FFD700"), 
                  QColor("#87CEEB"), QColor("#98FB98")};
        colorNames = {"浅灰", "金色", "天蓝", "浅绿"};
        currentIndex = 0;

        // 创建按钮
        button = new QPushButton(this);
        button->setText("当前颜色: " + colorNames[currentIndex]);
        button->setMinimumHeight(40);

        // 布局
        QVBoxLayout *layout = new QVBoxLayout(this);
        layout->addWidget(button);

        // 设置初始背景
        setAutoFillBackground(true);
        updateBackground();

        // 连接信号槽
        connect(button, &QPushButton::clicked, this, &ColorWindow::changeColor);
    }

private slots:
    void changeColor() {
        currentIndex = (currentIndex + 1) % colors.size();
        updateBackground();
    }

private:
    void updateBackground() {
        QPalette pal = palette();
        pal.setColor(QPalette::Window, colors[currentIndex]);
        setPalette(pal);
        button->setText("当前颜色: " + colorNames[currentIndex]);
    }

    QPushButton *button;
    QList<QColor> colors;
    QStringList colorNames;
    int currentIndex;
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    ColorWindow window;
    window.setWindowTitle("按钮点击事件处理");
    window.resize(300, 200);
    window.show();
    return app.exec();
}

编译与运行

# 在项目目录下创建CMakeLists.txt(内容见下方说明)
mkdir build && cd build
cmake ..
make
./ColorButtonDemo

CMakeLists.txt最小配置:

cmake_minimum_required(VERSION 3.16)
project(ColorButtonDemo)
find_package(Qt6 COMPONENTS Widgets REQUIRED)  # Qt5则改为 find_package(Qt5 COMPONENTS Widgets)
qt_standard_project_setup()  # Qt6专用,Qt5可省略
add_executable(ColorButtonDemo main.cpp)
target_link_libraries(ColorButtonDemo Qt::Widgets)

验证方法

运行程序后,窗口初始背景为浅灰色,按钮文字显示“当前颜色: 浅灰”。每点击一次按钮,窗口背景依次切换为金色、天蓝、浅绿,再回到浅灰循环;按钮文字同步更新为对应的颜色名称。若点击4次后颜色循环回到初始状态,且窗口背景与按钮文字始终一致,则判定功能正常。

关键说明

信号槽连接使用connect(button, &QPushButton::clicked, this, &ColorWindow::changeColor),这是Qt 5/6推荐的函数指针语法,编译期即可检查参数类型。背景色通过QPalette设置,需先调用setAutoFillBackground(true)使背景色生效。颜色列表和名称列表通过QList和QStringList存储,使用取模运算实现循环切换。