pyqt是封装qt,开发夸平台的桌面应用程序的python模块,去年就接触过,不深。最近一段时间重新使用起来。以下的内容在互联网上都能搜索得到,都是经过我的实践过。

1. 根据屏幕大小将窗口移动到合适的位置

        desktop = QApplication.desktop().availableGeometry()#获取屏幕大小
        mw = self.geometry()
        mw.moveTo(desktop.width()/2-mw.width()/2,desktop.height()/2-mw.height()/2)
        self.setGeometry(mw)

2. 实现从登录框到主界面

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import  uic

class LoginWindow(QDialog):
    def __init__(self):
    super(LoginWindow, self).__init__()
    self.ui = uic.loadUi('ui/login.ui',self)
    self.connect(self.ui.ok_botton,SIGNAL("clicked()"),self.check_user)
    def check_user(self,username,password):
    checked = False
    #验证过程
    if checked:
        #QDialog的DialogCode有(Rejected, Accepted)
        self.accept()

class Main(QMainWindow):
    #主窗口


if __name__ == '__main__':
    app = QApplication(sys.argv) 
    login = LoginWindow()
    if login.exec_() == QDialog.Accepted():#不能把login show出来,要用exec_()
        main = Main()
        main.show()
    sys.exit(app.exec_())

3. 设置背景图,圆角窗口

#保证图片为圆角,如果窗口是可resize的,此方法就不能用了
def set_backgroud_image(self,path):     pixmap = QPixmap(path) palette = QPalette() palette.setBrush(QPalette.Background, QBrush(pixmap)) self.setPalette(palette) self.resize(pixmap.size()) self.setMask(pixmap.mask())

4. 无边框,做界面美化的,特别是有互联网范的话,这个是必须做的

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import  uic

class BaseWidget(QWidget):
    def __init__(self):
    super(BaseWidget, self).__init__()
    self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowSystemMenuHint )#WindowFlags必须设置为FramelessWindowHint
    self.mouse_press = False
    self.resizeAble = False
    self.band = QRubberBand(QRubberBand.Rectangle)#用额外的正方形实现resize 
    self.band.setStyleSheet("background:rgba(170, 167, 151, 100);")


    def set_band(self):
        self.band.setMaximumSize(self.maximumSize())
        self.band.setMinimumSize(self.minimumSize())
    
    #重载mousePressEvent方法,点击左键移动窗口
    def mousePressEvent(self,event):
        if event.button() == Qt.LeftButton:
            self.mouse_press = True
            self.resizeAble = False
            self.move_point = event.globalPos() - self.pos()
        event.accept()


    #重载mouseMoveEvent,注意mouseTracking设置为True。
    def mouseMoveEvent(self, event):
        pos = event.pos()
        me = self.geometry()
        move_pos = event.globalPos()
        self.setCursor(Qt.ArrowCursor)
        if abs(pos.x() - me.width())**2 + abs(pos.y() - me.height())**2 < abs_**2:
       #鼠标移动到右下角,光标变化。这里同样可以去实现鼠标移动到边框,四角时光标的变化     self.setCursor(Qt.SizeFDiagCursor)     self.resizeAble
= True if self.mouse_press and not self.resizeAble: self.move(move_pos - self.move_point)     if self.mouse_press and self.resizeAble:
        #不要去实时变化窗口的大小,如果移动快了,会导致鼠标移除窗口,从而无法监听到鼠标移动事件     self.band.setGeometry(QRect(self.pos(), event.globalPos()))     self.band.show()     band_geometry
= self.band.geometry()     if move_pos.x() == band_geometry.right() and move_pos.y() == band_geometry.bottom():     self.setCursor(Qt.SizeFDiagCursor) event.accept() def mouseDoubleClickEvent(self,event):     if self.maximumSize() == self.minimumSize():     return     if not self.isMaximized():     self.showMaximized()     else:     self.showNormal() def mouseReleaseEvent(self, event):     self.band.hide()     if self.mouse_press and self.resizeAble:     self.setGeometry(self.band.geometry()) self.mouse_press = False     self.resizeAble = False event.accept()

 5. 类似qq托盘消息闪动。使用QTimer的timeout,改变托盘图标

#coding=utf-8

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class QQSystemTrayIcon(QSystemTrayIcon):
    def __init__(self,path='res/images/logo/logo16.png'):
        QSystemTrayIcon.__init__(self)
        self.path = path
        self.times = QTimer()
        self.times.setSingleShot(False)#设置为False,只触发一次事件
        self.times.setInterval(800)#timeout的时间,单位是毫秒

        self.flags = True
    
        icon = QIcon(self.path)
        self.setIcon(icon)

        self.connect(self.times,SIGNAL('timeout()'),self.change_icon)

    def activated_unread_chat(self):
        if not self.times.isActive():
            self.times.start()

    def activated_readed(self):
        if self.times.isActive():
            self.times.stop()
        self.setIcon(QIcon(self.path))


    def change_icon(self):
        if self.flags:
            self.setIcon(QIcon())
            self.flags = False
        else:
            self.setIcon(QIcon(self.path))
            self.flags = True

    
    

6. 右键菜单。重载contextMenuEvent事件,需要注意的是,右键菜单时间响应,对于左右键的有效的。我没有找到好的办法,就自定义了一个Menu。将左键点击屏蔽掉

class Menu(QMenu):
    def __init__(self,parent=None):
        super(Menu, self).__init__(parent)

    def mousePressEvent(self,event):
        if event.button() == Qt.RightButton:
            if self.isVisible():
                self.close()
        return
        super(Menu, self).mousePressEvent(event)

    def mouseReleaseEvent(self,event):
        if event.button() == Qt.RightButton:
            return
    super(Menu, self).mouseReleaseEvent(event)

7. QSettings的应用,QSettings是保存一些配置,有NativeFormat, IniFormat, InvalidFormat3种格式。

self.settings =  QSettings("config/config.ini", QSettings.IniFormat)
self.settings.setValue('LoginUser/Username','cc')
self.settings.value('LoginUser/Username')#返回是QVariant类型

8. QTabWidget 初始化的时候,里面的所有tab宽度是总和是QTabWidget的宽度。想在QTabWidget resize的时候,同样有这样的效果,需要重载resizeEvent

    #基本原理是通过style去设置宽度
def resizeEvent(self,event):     style = unicode(self.ui.tab.styleSheet())     styles = style.split('\n')[1:]     tab_width = self.width()/4.0     self.ui.tb_main.setStyleSheet("QTabBar::tab{width:%fpx;height:38px;alignment: center;padding-left: %ipx;}\n"%(tab_width/2+35,tab_width/2-35)+'\n'.join(styles))     event.accept()