qt之自定义界面

建立一个QWidget类型的工程,在该cpp的构造函数中写入:

    setWindowFlags(Qt::FramelessWindowHint |Qt::WindowStaysOnTopHint);//设置窗体标题栏隐藏并设置位于顶层
    setMouseTracking(true);//可获取鼠标跟踪效果

在该头文件中写一些变量和事件

public:
    QPoint move_point;//移动的距离
    bool mouse_press;//鼠标按下
private:
    void mousePressEvent(QMouseEvent *event);//鼠标按下事件
    void mouseReleaseEvent(QMouseEvent *event);//鼠标释放事件
    void mouseMoveEvent(QMouseEvent *event);//鼠标移动事件

在该cpp中写这三个函数的方法体

void windowTest::mousePressEvent(QMouseEvent *event)
{
    if (event->button()==Qt::LeftButton)
    {
        mouse_press = true;
        move_point = event->pos();
    }
}

void windowTest::mouseReleaseEvent(QMouseEvent *event)
{
    mouse_press = false;
}

void windowTest::mouseMoveEvent(QMouseEvent *event)
{
    if (mouse_press)
    {
        QPoint move_pos = event->globalPos();
        this->move(move_pos - move_point);
    }
}

在构造函数中写入加载背景:

    int width = this->width();
    QToolButton *minButton = new QToolButton(this);
    QToolButton *closeButton = new QToolButton(this);

    QPixmap minPix = style()->standardPixmap(QStyle::SP_TitleBarMinButton);
    QPixmap closePix = style()->standardPixmap(QStyle::SP_TitleBarCloseButton);

    minButton->setIcon(minPix);
    closeButton->setIcon(closePix);

    minButton->setGeometry(width - 46, 5, 20, 20);
    closeButton->setGeometry(width - 25, 5, 20, 20);

    minButton->setToolTip(tr("最小化"));
    closeButton->setToolTip(tr("关闭"));

    minButton->setStyleSheet("background-color:transparent");
    closeButton->setStyleSheet("background-color:transparent");

    //这个是用图片作为背景
    //QLabel *background = new QLabel(this);
    //background->setPixmap(QPixmap("D:/greatmap/dev/trunk/bin/Resources/Styles/Style0/Images/Dialog/close.png"));
    //background->setGeometry(0, 0, this->width(), this->height());
    //background->setScaledContents(true);

    QLabel *background = new QLabel(this);
    background->setStyleSheet("background-color:blue");
    background->setGeometry(0, 0, this->width(), this->height());

如何使用图片作为背景的话,重写paintEvent函数:

virtual void paintEvent(QPaintEvent *);

void windowTest::paintEvent(QPaintEvent *)
{
    QBitmap bitmap(this->size());
    bitmap.fill();
    QPainter painter(&bitmap);
    QPixmap pixmap("D:/greatmap/dev/trunk/bin/Resources/Styles/Style0/Images/Dialog/close.png");
    painter.drawPixmap(this->rect(), pixmap);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值