如何在QT中向窗口小部件的角落添加按钮?

时间:2012-02-21 19:14:24

标签: c++ qt layout

我正在尝试显示正方形图像并在右上角有一个X(图像的一半在外面),以关闭图像。我不知道一个允许我这样做的布局管理器。我该如何实现呢?

+---------O <- close button
|         |
|         |
+---------+

1 个答案:

答案 0 :(得分:3)

这里要实施很多。我通过以下方式完成了这项工作:

步骤1.对QLabel进行子类化,以便捕获鼠标点击。在标题声明信号中单击并按下,并覆盖正确的鼠标事件。

LabelButton::LabelButton(QWidget *parent) : QLabel(parent)
{
}
void LabelButton::mouseReleaseEvent(QMouseEvent *event){
    emit Clicked();
    event->accept();
}
void LabelButton::mousePressEvent(QMouseEvent *event){
    emit Pressed();
    event->accept();
}

步骤2.将一个名为xbutton的LabelButton添加到您想要的位置的小部件中,其中包含一个圆形的“x”图像。

示例(这将在您的setupUi函数中):

...
xbutton = new LabelButton(MainWidget);
xbutton->setObjectName(QString::fromUtf8("xbutton"));
xbutton->setGeometry(QRect(0, 0, 31, 31));
xbutton->setPixmap(QPixmap(QString::fromUtf8(":/xbutton.gif")));
xbutton->setAlignment(Qt::AlignCenter);
...

步骤3.创建小部件。将其背景设置为透明,并确保其大小包含“x”关闭按钮的空间。注意:将背景设置为透明意味着您的窗口小部件必须包含一些接受用户输入的子窗口小部件。

示例:

mywidget::mywidget(QWidget *parent): QWidget(parent){
    setupUi(this);
    moving=false; // notice that you must declare this bool for Step 4.
    offset=QPoint(0,0); // Also a QPoint for Step 4
#if defined(Q_WS_MAC) //These values worked for me with the Mac OS 10.5 SDK
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint | Qt::Window);
    QPalette pal = this->palette();
    pal.setColor(this->backgroundRole(), Qt::transparent);
    this->setPalette(pal);
#elif defined(Q_WS_WIN)//These values worked for me on Windows XP/Vista/7
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint |Qt::FramelessWindowHint | Qt::Window);
    setStyleSheet("background:transparent;");
    setAttribute(Qt::WA_TranslucentBackground);
#endif
    connect(xbutton,SIGNAL(Clicked()),this,SLOT(hide()));
}

现在您拥有了最初所需的功能。单击x按钮时,窗口将关闭。但是在实现之前你不会有正常的移动功能。

步骤4.为您的小部件实施移动功能。

/*
 FUNCTION:mousePressEvent
 used to help move the widget since there is no title bar, sets the initial offset of the mouse
 */
void mywidget::mousePressEvent(QMouseEvent *event){
    if((event->button() == Qt::LeftButton)) {
        moving = true;
        offset = event->globalPos() - this->pos();
    }
}
/*
 FUNCTION:mouseReleaseEvent
 used to help move the widget since there is no title bar, releases the "moving" attribute
 */
void mywidget::mouseReleaseEvent(QMouseEvent *event){
    if(event->button() == Qt::LeftButton) {
        moving = false;
    }
}
/*
 FUNCTION:mouseMoveEvent
 used to help move the widget since there is no title bar
 */
void mywidget::mouseMoveEvent(QMouseEvent *event){
    if(moving){
    QPoint global = event->globalPos();
    this->setGeometry(global.x()-offset.x(),global.y()-offset.y(),this->width(),this->height());
    }
}

我发现这种方式对我来说最有用,因为我需要从我定制的光滑外观小部件中获得许多功能。

我非常喜欢有创意的用户界面,我希望你完成后看起来非常时尚!

相关问题