【问题标题】:I want to create a custom title bar in qt我想在 qt 中创建一个自定义标题栏
【发布时间】:2017-04-10 09:22:14
【问题描述】:

我想在 qt 中创建一个自定义标题栏。

所以我查找了一些示例并遵循了它们。 这是应用示例的代码。

小部件头文件:

#include <QWidget>
#include <QMouseEvent>

class KcWdTitlebar :public QWidget
{
private:
    QWidget *m_parent;
    QPoint m_pCursor;

public:
    KcWdTitlebar( QWidget *parent) ;

protected:
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
};

小部件 cpp:

KcWdTitlebar::KcWdTitlebar(QWidget *parent ) :m_parent(parent)
{
    QLabel *title = new QLabel(parent->windowTitle());
    QPushButton *pPB = new QPushButton ("x");

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->addWidget(title);
    layout->addWidget(pPB);

    connect(pPB,SIGNAL(clicked()),parent,SLOT(close()));
}

void KcWdTitlebar::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_pCursor = event->globalPos() - geometry().topLeft();
        event->accept();
    }
}

void KcWdTitlebar::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        m_parent->move(event->globalPos() - m_pCursor);
        event->accept();
    }
}

主窗口标题:

#include <QMainWindow>
#include "KcWdTitlebar.h"

namespace Ui {
class mainwindow;
}

class mainwindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit mainwindow(QWidget *parent = 0);
    ~mainwindow();

private:
    KcWdTitlebar *m_title;
    Ui::mainwindow *ui;
};

ma​​inwidow cpp:

mainwindow::mainwindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::mainwindow)
{
    ui->setupUi(this);
    m_title = new KcWdTitlebar(this);
    ui->verticalLayout->addWidget(m_title);

}

当我运行这段代码时, 单击并拖动 KcWdTitle 部分将导致主窗口比我单击的点更远。

我应该修复代码的哪些部分?

希望大家都能听懂我的英文。

【问题讨论】:

  • 尝试更改:void KcWdTitlebar::mousePressEvent(QMouseEvent *event)void KcWdTitlebar::mouseMoveEvent(QMouseEvent *event),看看行为是否有变化。如果是这种情况,那么这是您应该更改的部分。
  • Ui::mainwindow 的完整定义在哪里?
  • @DavidGrayson Ui::mainwindow 中没有太多内容。我刚刚将 KcWdTitlebar 添加到框架的顶部。

标签: c++ qt qwidget


【解决方案1】:

您需要更改mousePressEvent() 以减去MainWindow 几何而不是标题栏的几何。

变化:

m_pCursor = event->globalPos() - geometry().topLeft();

到这里:

m_pCursor = event->globalPos() - m_parent->geometry().topLeft();

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    相关资源
    最近更新 更多