1. 程式人生 > >pyqt實現自定義視窗拖動大小,到桌面邊框自動影藏

pyqt實現自定義視窗拖動大小,到桌面邊框自動影藏

#-*- coding:utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys  
from ctypes import *
from time import sleep
import time
import threading
import PyQt4
from PyQt4.Qt import pyqtSignal
from win32con import *


key = 50
hotkeyId = 3
xdesktop=0
keyhot={"hokeyflag":True}
hokeyflag=True
PADDING=4

dictEnum={'UP':0,'DOWN':1,'LEFT':2,'RIGHT':3,'LEFTTOP':4,'LEFTBOTTOM':5,'RIGHTTOP':6,'RIGHTBOTTOM':7,'NONE':8}
dictRect={'width':200,'height':300}


class POINT(Structure):
    _fields_=[("x",c_ulong),("y",c_ulong)]
    
class MSG(Structure):
    _fields_ = [('hwnd', c_int),
                ('message', c_uint),
                ('wParam', c_int),
                ('lParam', c_int),
                ('time', c_int),
                ('pt', POINT)]
    
if not windll.user32.RegisterHotKey(None,hotkeyId,MOD_ALT,key):
    sys.exit("Can't Rigister Hotkey")



class threadPoint(QThread):
    mysignal=pyqtSignal(int)
    def __init__(self,tyPoint,tyHeight,parent=None):
        super(threadPoint,self).__init__(parent)
        self.type=tyPoint
        self.height=tyHeight
    def run(self):
        while True:
            orig=POINT()
            windll.user32.GetCursorPos(byref(orig))          
            if orig.y in range(self.height,self.height+dictRect['height']):
                if orig.x in range(-5,5) and self.type=="Left":
                    self.mysignal.emit(1)
                    break
                elif orig.x in range(xdesktop-5,xdesktop+5) and self.type=="Right":
                    self.mysignal.emit(2)
                    break
            elif orig.x in range(self.height,self.height+dictRect['width']):
                if orig.y in range(-5,5) and self.type=="Top":
                    self.mysignal.emit(3)
                    break    
            time.sleep(0.2)
            
        self.deleteLater()
            
            

     

class Myqq(QWidget):
    def __init__(self,parent=None):
        super(Myqq,self).__init__(parent)
        self.resize(dictRect['width'],dictRect['height'])
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.mousePress=False
        self.xWidth=QApplication.desktop().width()-self.width()
        self.xStep=self.width()/5;
        self.yStep=self.height()/5;
        self.setAutoFillBackground(True)
        self.setPalette(QPalette(QColor("yellow")))
        self.btn=QPushButton("ceshi",self)
        self.btn.move(50,50)
        self.btn.clicked.connect(self.close)
        
        self.dir = dictEnum['NONE']
        
        self.setMouseTracking(True)
       
    def resizeEvent(self, *args, **kwargs):
        dictRect['width']=self.width()
        dictRect['height']=self.height()
        self.xStep=self.width()/5;
        self.yStep=self.height()/5;
        return QWidget.resizeEvent(self, *args, **kwargs)
    
    def mouseMoveEvent(self, event):
        gloPoint=event.globalPos()
        rect=self.rect()
        t1 = self.mapToGlobal(rect.topLeft())
        rb = self.mapToGlobal(rect.bottomRight())
        
        if not self.mousePress:
            self.dragRegion(gloPoint)
        else:
            if self.dir != dictEnum['NONE']:
                rmove=QRect(t1,rb)
                if self.dir == dictEnum['LEFT']:
                    if(rb.x() -gloPoint.x() <= self.minimumWidth()):
                        rmove.setX(t1.x())
                    else:
                        rmove.setX(gloPoint.x())
                elif self.dir == dictEnum['RIGHT']:
                    rmove.setWidth(gloPoint.x()-t1.x())
                elif self.dir == dictEnum['UP']:
                    if rb.y() - gloPoint.y() <= self.minimumHeight():
                        rmove.setY((t1.y()))
                    else:
                        rmove.setY(gloPoint.y())
                elif self.dir == dictEnum['DOWN']:
                    rmove.setHeight(gloPoint.y()-t1.y())
                elif self.dir == dictEnum['LEFTTOP']:
                    if rb.x() - gloPoint.x() <= self.minimumWidth():
                        rmove.setX(t1.x())
                    else:
                        rmove.setX(gloPoint.x()) 
                    if rb.y() - gloPoint.y() <= self.minimumHeight():
                        rmove.setY(t1.y())
                    else:
                        rmove.setY(gloPoint.y())
                elif self.dir == dictEnum['RIGHTTOP']:
                    rmove.setWidth(gloPoint.x()-t1.x())
                    rmove.setY(gloPoint.y())
                elif self.dir == dictEnum['LEFTBOTTOM']:
                    rmove.setX(gloPoint.x())
                    rmove.setHeight(gloPoint.y()-t1.y())
                elif self.dir == dictEnum['RIGHTBOTTOM']:
                    rmove.setWidth(gloPoint.x()-t1.x())
                    rmove.setHeight(gloPoint.y()-t1.y())
                else:
                    pass
                self.setGeometry(rmove)
            else:                     
                if  self.mousePress and event.buttons()== Qt.LeftButton:            
                    tmp=event.globalPos()-self.mousePoint
                    if tmp.x() > xdesktop-self.width()-5:
                        self.move(xdesktop-self.width()-5,self.geometry().y())
                    elif tmp.x() < 5:
                        self.move(4,self.geometry().y())
                    elif tmp.y() < 2:
                        self.move(self.geometry().x(),2)
                    else:
                        self.move(event.globalPos()-self.mousePoint)
                    event.accept()
            
  
    def mousePressEvent(self, event):
        if(event.button()==Qt.LeftButton):
            self.mousePress=True
            if self.dir != dictEnum['NONE']:
                self.mouseGrabber()
            else:            
                self.mousePoint=event.globalPos()-self.pos()                
            event.accept()
             
     
        
    def mouseReleaseEvent(self, event):
        self.mousePress=False 
        if self.dir != dictEnum['NONE']:
            self.releaseMouse()
            self.setCursor(QCursor(Qt.ArrowCursor)) 
     
    def enterEvent(self,event):
         
        pass
    
    
     
    def leaveEvent(self, event):
       
        print(self.geometry().x(),self.geometry().y())
        if(self.geometry().x() in range(0,1)):
            for i in range(5):
                self.move(self.geometry().x()-self.xStep,self.geometry().y())
                time.sleep(0.05)
            self.tmpThread=threadPoint("Left",self.geometry().y())
            self.tmpThread.mysignal.connect(self.reCoveryUi)
            self.tmpThread.start()
            event.accept()
         
        elif(self.geometry().x() in range(self.xWidth-5,self.xWidth+5)):
            for i in range(5):
                self.move(self.geometry().x()+self.xStep,self.geometry().y())
                time.sleep(0.05)
            self.tmpThread=threadPoint("Right",self.geometry().y())
            self.tmpThread.mysignal.connect(self.reCoveryUi)
            self.tmpThread.start()
            event.accept()
         
        elif(self.geometry().y() in range(0,3)):
            for i in range(5):
                self.move(self.geometry().x(),self.geometry().y()-self.yStep)
                time.sleep(0.05)
            self.tmpThread=threadPoint("Top",self.geometry().x())
            self.tmpThread.mysignal.connect(self.reCoveryUi)
            self.tmpThread.start()
            event.accept()
             
             
 
         
    def closeEvent(self, *args, **kwargs):
        keyhot["hokeyflag"]=False
        print("xiongzhiping",keyhot["hokeyflag"])
        return QWidget.closeEvent(self, *args, **kwargs)
             
    def eventFilter(self, event):
        print(event.pos())
         
     
    def reCoveryUi(self,value):
        if  value == 1:
            for i in range(5):
                self.move(self.geometry().x()+self.xStep,self.geometry().y())
                time.sleep(0.05)   
        elif value==2:
            for i in range(5):
                self.move(self.geometry().x()-self.xStep,self.geometry().y())
                time.sleep(0.05)  
        elif value==3:
            for i in range(5):
                self.move(self.geometry().x(),self.geometry().y()+self.yStep)
                time.sleep(0.05)
            
    def dragRegion(self,cursorGlobalPoint):
        rect=self.rect()
        t1=self.mapToGlobal(rect.topLeft())
        rb=self.mapToGlobal(rect.bottomRight())
        
        x=cursorGlobalPoint.x()
        y=cursorGlobalPoint.y()
        
        if (x in range(t1.x(),t1.x()+PADDING) and y in range(t1.y(),t1.y()+PADDING)):
            self.dir=dictEnum['LEFTTOP']
            self.setCursor(QCursor(Qt.SizeFDiagCursor))
        elif(x in range(rb.x()-PADDING,rb.x()) and y in range(rb.y()-PADDING,rb.y())):
            self.dir=dictEnum['RIGHTBOTTOM']
            self.setCursor(QCursor(Qt.SizeFDiagCursor))
        elif(x in range(t1.x(),t1.x()+PADDING) and y in range(rb.y()-PADDING,rb.y())):
            self.dir=dictEnum['LEFTBOTTOM']
            self.setCursor(QCursor(Qt.SizeBDiagCursor))
        elif(x in range(rb.x()-PADDING,rb.x()) and y in range(t1.y(),t1.y()+PADDING)):
            self.dir=dictEnum['RIGHTTOP']
            self.setCursor(QCursor(Qt.SizeBDiagCursor))
        elif(x in range(t1.x(),t1.x()+PADDING)):
            self.dir=dictEnum['LEFT']
            self.setCursor(QCursor(Qt.SizeHorCursor))
        elif(x in range(rb.x()-PADDING,rb.x())):
            self.dir=dictEnum['RIGHT']
            self.setCursor(QCursor(Qt.SizeHorCursor))
        elif(y in range(t1.y(),t1.y()+PADDING)):
            self.dir=dictEnum['UP']
            self.setCursor(QCursor(Qt.SizeVerCursor))
        elif(y in range(rb.y()-PADDING,rb.y())):
            self.dir=dictEnum['DOWN']
            self.setCursor(QCursor(Qt.SizeVerCursor))
        else:
            self.dir = dictEnum['NONE']
            self.setCursor(QCursor(Qt.ArrowCursor))
            


app=QApplication(sys.argv)
xdesktop=app.desktop().width()
msg = MSG()
widget=Myqq()
widget.show()
while keyhot["hokeyflag"]:  
    if (windll.user32.GetMessageA(byref(msg), None, 0, 0) != 0):
        if(msg.wParam==WM_HOTKEY and msg.time==hotkeyId):
            print(msg.wParam,msg.time,msg.lParam,msg.message)     
            if widget.isHidden():
                widget.show()
            else:
                widget.hide()
        windll.user32.TranslateMessage(byref(msg))
        windll.user32.DispatchMessageA(byref(msg))
if keyhot["hokeyflag"]==False:
    sys.exit()
        
sys.exit(app.exec_())