Qt5学习之路02:使用继承自QWidget类的派生类创建空的窗口,重载键盘事件处理函数,添加程序图标

main.cpp

#include 
#include "mywidget.h"
#include 
int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    MyWidget w;
    w.resize(640, 320);
    w.move(400, 200);
    w.setWindowIcon(QIcon(":/new/prefix1/robot.png")); //为程序添加图标
    w.show();

    return app.exec();
}

mywidget.h

#ifndef MYWIDGET_H
#define MYWIDGET_H
#include 

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();
protected:
    void keyPressEvent(QKeyEvent *event);

signals:

public slots:
};

#endif // MYWIDGET_H

mywidget.cpp

#include "mywidget.h"
#include 


MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{

}

MyWidget::~MyWidget()
{

}

void MyWidget::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier){
        if(event->key() == Qt::Key_Q) //键盘事件处理函数, 按下快捷键 Ctrl + Q 退出程序
        {
            this->close();
        }
        if(event->key() == Qt::Key_L) //键盘事件处理函数, 按下快捷键 Ctrl + L 最大化程序窗口
        {
            this->setWindowState(Qt::WindowMaximized);
        }
        if(event->key() == Qt::Key_S) //键盘事件处理函数, 按下快捷键 Ctrl + S 最小化程序窗口
        {
            this->setWindowState(Qt::WindowMinimized);
        }
        if(event->key() == Qt::Key_N) //键盘事件处理函数, 按下快捷键 Ctrl + N 使程序窗口回到正常状态
        {
            this->setWindowState(Qt::WindowNoState);
        }
    }
    else{
        QWidget::keyPressEvent(event);
    }
}

resources.qrc

<RCC>
    <qresource prefix="/new/prefix1">
        <file>robot.pngfile>
    qresource>
RCC>

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

project(03_empty_window)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
find_package(Qt5 COMPONENTS Widgets REQUIRED)
add_executable(${PROJECT_NAME} "main.cpp" "mywidget.cpp" "mywidget.h" "resources.qrc")
target_link_libraries(${PROJECT_NAME} Qt5::Widgets)

编译运行结果如下:
Qt5学习之路02:使用继承自QWidget类的派生类创建空的窗口,重载键盘事件处理函数,添加程序图标_第1张图片

你可能感兴趣的:(Qt5)