我想顯示一個正方形的圖像,並在右上角有一個X(一半在圖像的一半以外)來關閉圖像。我不知道佈局經理會允許我這樣做。我如何實現這一點?如何將按鈕添加到QT中的小部件的角落?
+---------O <- close button | | | | +---------+
我想顯示一個正方形的圖像,並在右上角有一個X(一半在圖像的一半以外)來關閉圖像。我不知道佈局經理會允許我這樣做。我如何實現這一點?如何將按鈕添加到QT中的小部件的角落?
+---------O <- close button | | | | +---------+
這裏會有很多實現。我已經通過以下方式實現了這一點:
第1步。子類QLabel使捕獲鼠標點擊成爲可能。在標題中聲明信號Clicked和Pressed,並覆蓋正確的鼠標事件。
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在你想要的位置包含圓形「X」形象窗口小部件的LabelButton。
示例(這將是你的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步:創建你的widget。將其背景設置爲透明,並確保其大小包含'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());
}
}
我發現這種方式是最對我有用處,因爲我需要很多功能我的個性圓滑的窗口設計的。
我真的很喜歡創造性的用戶界面,我希望你看起來非常時尚,當你完成!
如果你被困在邏輯上,它會像這樣:創建一個無邊框畫布,大小爲基本圖像+ X圖像大小的一半。將基本圖像放置在左下方。將X圖像放在基本圖像頂部,位於右上角。 – 2012-02-21 20:20:23