【问题标题】:Removing title bar from Qt application从 Qt 应用程序中删除标题栏
【发布时间】:2015-01-10 08:13:52
【问题描述】:

我使用 Qt Creator 创建了一个应用程序。因为我希望它看起来与普通的 Windows 应用程序不同,所以我删除了 Windows 标题栏。但是,没有标题栏,我无法移动、最小化和最大化应用程序。如果可能的话,我希望通过按住菜单栏来移动我的应用程序,并将在 OS X 应用程序中使用的三个彩色圆形按钮放在菜单栏的右上角。这在 Qt 中可行吗?

【问题讨论】:

  • 我不认为它是重复的。从我读到的内容来看,这个问题是针对 Mac 的,而这个问题是针对 Windows 的。
  • @user3734823,你说的是“Windows”、“windows”还是“windows”?我希望我没有错误地编辑它。如果是这种情况,您可能需要在标题中添加“on Windows”。
  • 是的,在 Qt 中任何事情都是可行的。您需要在窗口上调用setWindowFlags(Qt::FramelessWindowHint) 以删除标题栏,然后实现您自己的标题栏小部件,您需要在该小部件上添加 QMenuBar 并将其放置在标题栏的自然位置。当然,您必须自己实现所有鼠标事件、按钮(最小化/最大化/关闭)和样式。您还将失去 Aero 效果和阴影,如果需要,您还需要自己实现它们......

标签: c++ qt user-interface


【解决方案1】:

我将解释如何获得它的结构,但我会留给你来设置所有内容的样式并连接信号。

最好的办法是创建自己的 QWidget 类,称为“TitleBar”,并给它一个 QHBoxLayout。在“TitleBar”类中,创建另一个 QWidgetQHBoxLayout 以包含按钮。创建 3 QPushButtons 并将它们添加到其中。接下来,您需要创建自己的QMenuBar 类,名为“MenuBar”,这样您就可以获取鼠标事件并构建拖动机制。下面是一些示例代码,说明您如何完成此操作。

标题栏

TitleBar::TitleBar() :
    QWidget()
{

    QHBoxLayout *l = new QHBoxLayout();
    l->setContentsMargins(0, 0, 0, 0);
    setLayout(l);

    QWidget *buttonGroup = new QWidget();
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setContentsMargins(0, 0, 0, 0);

    QPushButton *minButton = new QPushButton("");
    QPushButton *maxButton = new QPushButton("");
    QPushButton *closeButton = new QPushButton("");

    buttonLayout->addWidget(minButton, Qt::AlignRight);
    buttonLayout->addWidget(maxButton, Qt::AlignRight);
    buttonLayout->addWidget(closeButton, Qt::AlignRight);

    buttonGroup->setLayout(buttonLayout);
    buttonGroup->setFixedSize(buttonGroup->sizeHint());

    MenuBar *bar = new MenuBar();
    bar->addMenu("&File");

    l->addWidget(bar);
    l->addWidget(buttonGroup);

}

菜单栏

void MenuBar::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        QPointF newPos = (event->localPos() - dragPos) + window()->pos();
        window()->move(newPos.x(), newPos.y());
    }
    else
        QMenuBar::mouseMoveEvent(event);
}

void MenuBar::mousePressEvent(QMouseEvent *event)
{
    dragPos = event->localPos();
    QMenuBar::mousePressEvent(event);
}

然后,您可以将“TitleBar”类添加到您的小部件的主布局中并进行顶部对齐,一切都很好!现在这并不完美,但我认为它可以完成工作。

这是一个使用此方法的示例项目:http://www.filedropper.com/menubartest

【讨论】:

  • 我按照您的建议尝试了,但一直收到此错误消息,语法错误:mssing;在标识符 QtCoreModule 之前
  • 哦,顺便说一句,我使用提升的方法添加了自定义小部件,并且在titlebar.h中包含了自定义菜单栏类。这可能是问题的原因吗?
  • 我不确定。我在答案中使用此方法发布了一个示例项目。只需将菜单栏和标题栏类复制到您的项目中即可。
  • 有没有办法不使用localpos?因为我的 QT 版本不支持 localpos() 但 globalpos()
  • 然后使用pos()。你应该认真考虑升级到 Qt5
猜你喜欢
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 2015-01-16
  • 2016-10-25
  • 1970-01-01
  • 2021-09-02
相关资源
最近更新 更多