我将解释如何获得它的结构,但我会留给你来设置所有内容的样式并连接信号。
最好的办法是创建自己的 QWidget 类,称为“TitleBar”,并给它一个 QHBoxLayout。在“TitleBar”类中,创建另一个 QWidget 和 QHBoxLayout 以包含按钮。创建 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