Qt 實現點擊主窗口內任意位置,在其位置彈窗彈窗,且彈窗必須在主窗口的換位內


一、功能要求:

     實現點擊主窗口內任意位置,在其位置彈窗彈窗,且彈窗必須在主窗口的換位內。

    避免出現下面的問題:

    

二、功能分析:

      想法:

1、只要確定彈窗左上角的合理位置就可以了。

2、合理位置: 簡單的一種就是保證其必在主窗口內。思路就是,判斷彈窗左上角和右下角的坐標值是否超過主窗口的邊界值來重新設置彈窗的左上角的坐標值。

三、代碼實現:

 1 // mouseGPos : 當前鼠標的絕對坐標  2 // pMainWgt : 主窗口  3 // pPopWgt : 彈窗
 4 QPoint CToolBarWgt::getFixGlobalPos(QPoint mouseGPos, QWidget* pMainWgt, QWidget* pPopWgt)  5 {  6     QPoint mianGPoint = pMainWgt->mapToGlobal(pMainWgt->pos());  7     int nMainLeft = mianGPoint.x();  8     int nMainTop = mianGPoint.y();  9     int nMainRight = mianGPoint.x()+ pMainWgt->width(); 10     int nMainBottom = mianGPoint.y() + pMainWgt->height(); 11  
12     int nPopLeft = mouseGPos.x() - pPopWgt->width()/2 ; 13     int nPopTop = mouseGPos.y() - pPopWgt->height(); 14     int nPopRight = mouseGPos.x() + pPopWgt->width()/2; 15     int nPopBottom = mouseGPos.y(); 16  
17     // 最終要確定的只有左上角的坐標位置: 
18     nPopLeft = nPopLeft < nMainLeft ? nMainLeft: nPopLeft;  // 彈窗左邊超出主窗口,賦值為主窗口邊界值。
19     nPopTop = nPopTop < nMainTop ? nMainTop : nPopTop; //彈窗上部分超出主窗口上部值,賦值為主窗口上半邊界值。
20     nPopLeft = nPopRight > nMainRight ? nPopLeft - (nPopRight - nMainRight) : nPopLeft; //彈窗右側超出主窗口右側邊界值,則彈窗左側值向左移動超出的部分
21     nPopTop = nPopBottom > nMainBottom ? nPopTop - (nPopBottom - nMainBottom): nPopTop; //彈窗下側超出主窗口下側邊界值,則彈窗上側值向上移動超出的部分 22     // 返回的QPoint是絕對坐標。
23     return QPoint(nPopLeft, nPopTop); 24 }

四、疑問

   為什么彈窗明明有設置父類,並且其父類也有設置主窗口為父類。當時該彈窗在this->move(x,y)的時候,x,y卻是絕對坐標下的值。【ps:上面內容絕對可靠沒錯】

   突然想到是否為下面內容中某個設置后導致的

1     setWindowFlags(Qt::FramelessWindowHint | Qt::Tool); 2     setAttribute(Qt::WA_TranslucentBackground, true);

其中彈窗是繼承於QWidget的窗口。

因為Qt4 文檔中說:

pos : QPoint This property holds the position of the widget within its parent widget. If the widget is a window, the position is that of the widget on the desktop, including its frame. When changing the position, the widget, if visible, receives a move event (moveEvent()) immediately. If the widget is not currently visible, it is guaranteed to receive an event before it is shown. By default, this property contains a position that refers to the origin.

結果:證實確實是 setWindowFlags(Qt::Tool)導致的move的時候是按照絕對坐標(顯示器)來移動的。

 因為把這個移除后,其move()就變成相對父對象的相對位置了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM