基于Anaconda3+Opencv-Python+Qt5+Pycharm+pytorch开发环境的PyQt5相关项目开发源代码(1)

PyQt5学习:

代码1:
import sys

from PyQt5.QtWidgets import QApplication,QWidget

if __name__ =='__main__':
  # 创建QApplication类的实例
   app =QApplication(sys.argv)
  # 创建一个窗口
   w =QWidget()
  # 设置窗口的尺寸
   w.resize(1600,800)
  #移动窗口
   w.move(300,300)
  # 设置窗口的标题
   w.setWindowTitle('第一个基于PyQt5的桌面应用')
  #显示窗口
   w.show()

   #进入程序的主循环、并通过exit函数确保主循环安全结束
   sys.exit(app.exec_())


代码2:显示创建的designer
import sys
import MainWindow_1#MainWindow_1是.ui转换而来的
from PyQt5.QtWidgets import QApplication, QMainWindow

if __name__=='__main__':
   app =QApplication(sys.argv)
   mainWindow =QMainWindow()
   ui =MainWindow_1.Ui_MainWindow()#可以修改MainWindow_1
   # 向主窗口添加控件
   ui.setupUi(mainWindow)
   mainWindow.show()
   sys.exit(app.exec_())


代码3:
import sys
from PyQt5.QtWidgets import QMainWindow,QApplication
from PyQt5.QtGui import QIcon

class FirstMainWin(QMainWindow):
   def __init__(self,parent =None):
      super(FirstMainWin,self).__init__(parent)

      #设置主窗口的标题
      self.setWindowTitle('第一个主窗口应用')

      #设置窗口尺寸
      self.resize(400,300)
      self.status =self.statusBar()
      self.status.showMessage('只存在5秒的信息',5000)
if __name__ =='__main__':
   app =QApplication(sys.argv)

   app.setWindowIcon(QIcon('E:/555/555/mydata3/train/images/000001.jpg'))
   main =FirstMainWin()
   main.show()

   sys.exit(app.exec_())


代码1:屏幕居中显示

# QDesktopWidget
import sys
from PyQt5.QtWidgets import QDesktopWidget,QMainWindow,QApplication
from PyQt5.QtGui import QIcon

class CenterForm(QMainWindow):
   def __init__(self,parent =None):
      super(CenterForm,self).__init__(parent)

      #设置主窗口的标题
      self.setWindowTitle('让窗口居中显示')

      #设置窗口尺寸
      self.resize(400,300)
      self.status =self.statusBar()
      self.status.showMessage('只存在5秒的信息',5000)
   def center(self):
      #获取屏幕坐标系
      screen =QDesktopWidget().screenGeometry()
      # 获取窗口坐标系
      size =self.geometry()
      newLeft =(screen.width()-size.width())/2
      newTop =(screen.height()-size.height())/2
      self.move(newLeft,newTop)
if __name__ =='__main__':
   app =QApplication(sys.argv)

   app.setWindowIcon(QIcon('E:/555/555/mydata3/train/images/000001.jpg'))
   main =CenterForm()
   main.show()

   sys.exit(app.exec_())

代码2:退出应用程序显示并点击退出代码
import sys
from PyQt5.QtWidgets import QHBoxLayout,QMainWindow,QApplication,QWidget,QPushButton

class QuitApplication(QMainWindow):
   def __init__(self):
      super(QuitApplication,self).__init__()
      self.resize(300,120)
      self.setWindowTitle('退出应用程序')

      #添加Button
      self.button1 =QPushButton('退出应用程序')
      # 将信号与槽关联
      self.button1.clicked.connect(self.onClink_Button)

      layout =QHBoxLayout()
      layout.addWidget(self.button1)

      mainFrame =QWidget()
      mainFrame.setLayout(layout)
      self.setCentralWidget(mainFrame)


   #按钮单击事件的方法(自定义的槽)
   def onClink_Button(self):
      sender =self.sender()
      print(sender.text() +'按钮按下')
      app =QApplication.instance()
      #退出应用程序
      app.quit()
if __name__ =='__main__':
     app =QApplication(sys.argv)


     main =QuitApplication()
     main.show()

     sys.exit(app.exec_())


代码3:QLabel控件--文本操作

# setAlignment():设置文本对齐方式
# setIndent():设置文本缩进
# text():获取文本内容
# setBuddy():设置伙伴关系
# setText():设置文本内容
# setWordWrap():设置是否允许换行
# 当鼠标滑过QLabel控件时触发:linkHovered
# 当鼠标单击QLabel控件时触发:linkActivated

import sys
from PyQt5.QtWidgets import QVBoxLayout, QMainWindow, QApplication, QLabel,QWidget
from PyQt5.QtGui import QPixmap,QPalette
from PyQt5.QtCore import Qt

class QLabelDemo(QWidget):
   def __init__(self):
      super().__init__()
      self.initUI()
   def initUI(self):
      label1 =QLabel(self)
      label2 = QLabel(self)
      label3 = QLabel(self)
      label4 = QLabel(self)

      label1.setText("这是一个文本标签.")
      label1.setAutoFillBackground(True)
      palette =QPalette()
      palette.setColor(QPalette.Window,Qt.blue)
      label1.setPalette(palette)
      label1.setAlignment(Qt.AlignCenter)

      label2.setText("欢迎使用Python GUI程序")
      label3.setAlignment(Qt.AlignCenter)
      label3.setToolTip('这是一个图片标签')
      label3.setPixmap(QPixmap("E:/555/555/mydata3/train/images/000001.jpg"))
      label4.setOpenExternalLinks(True)
      label4.setText("感谢关注")
      label4.setAlignment(Qt.AlignRight)
      label4.setToolTip('这是一个超链接')

      vbox =QVBoxLayout()
      vbox.addWidget(label1)
      vbox.addWidget(label2)
      vbox.addWidget(label3)
      vbox.addWidget(label4)

      label2.linkHovered.connect(self.linkHovered)
      label4.linkActivated.connect(self.linkClicked)

      self.setLayout(vbox)
      self.setWindowTitle('QLabel控件演示')


   def linkHovered(self):
      print('当鼠标滑过label2标签时,触发事件')
   def linkClicked(self):
      print('当鼠标单击label4标签时,触发事件')
if __name__ =='__main__':
   app =QApplication(sys.argv)
   #app.setWindowIcon(QIcon('E:/555/555/mydata3/train/images/000001.jpg'))
   main =QLabelDemo()
   main.show()
   sys.exit(app.exec_())


代码4:QLabel与伙伴控件

# Qlabel与伙伴控件

from PyQt5.QtWidgets import *
import sys

class QLabelBuddy(QDialog):
   def __init__(self):
      super().__init__()
      self.initUI()

   def initUI(self):
      self.setWindowTitle('QLabel与伙伴关系')

      nameLabel =QLabel('&Name',self)
      nameLineEdit =QLineEdit(self)
      #设置伙伴控件
      nameLabel.setBuddy(nameLineEdit)

      passwordLabel =QLabel('&Password',self)
      passwordLineEdit =QLineEdit(self)
      #设置伙伴控件
      passwordLabel.setBuddy(passwordLineEdit)

      btnOK =QPushButton('&OK')
      btnCancel =QPushButton('&Cancel')

      mainLayout =QGridLayout(self)

      mainLayout.addWidget(nameLabel,0,0)
      mainLayout.addWidget(nameLineEdit,0,1,1,2)

      mainLayout.addWidget(passwordLabel,1,0)
      mainLayout.addWidget(passwordLineEdit,1,1,1,2)

      mainLayout.addWidget(btnOK,2,1)
      mainLayout.addWidget(btnCancel,2,2)
if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QLabelBuddy()
   main.show()
   sys.exit(app.exec_())

代码5:QLineEdit控件与回显模式,功能:输入单行文本;回显模式(EchoMode)

# 4种回显模式(Normal/NoEcho/Password/PasswordEchoOnEdit)

from PyQt5.QtWidgets import *
import sys

class QlineEditEchoMode(QWidget):
   def __init__(self):
      super(QlineEditEchoMode,self).__init__()
      self.initUI()

   def initUI(self):
       self.setWindowTitle('文本输入框的回显模式')

       formLayout =QFormLayout()

       normalLineEdit =QLineEdit()
       noEchoLineEdit =QLineEdit()
       passwordLineEdit =QLineEdit()
       passwordEchoOnEditLineEdit =QLineEdit()

       formLayout.addRow("Normal", normalLineEdit)
       formLayout.addRow("NoEcho", noEchoLineEdit)
       formLayout.addRow("Password", passwordLineEdit)
       formLayout.addRow("PasswordEchoOnEdit", passwordEchoOnEditLineEdit)

       # placeholdertext
       normalLineEdit.setPlaceholderText("Normal")
       noEchoLineEdit.setPlaceholderText("NoEcho")
       passwordLineEdit.setPlaceholderText("password")
       passwordEchoOnEditLineEdit.setPlaceholderText("PasswordEchoOnEdit")

       normalLineEdit.setEchoMode(QLineEdit.Normal)
       noEchoLineEdit.setEchoMode(QLineEdit.NoEcho)
       passwordLineEdit.setEchoMode(QLineEdit.Password)
       passwordEchoOnEditLineEdit.setEchoMode(QLineEdit.PasswordEchoOnEdit)

       self.setLayout(formLayout)

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QlineEditEchoMode()
   main.show()
   sys.exit(app.exec_())

代码6:现在QLienEdit控件的输入(校验器),如限制只能输入整数、浮点数或满足一定条件的字符串

# 现在QLienEdit控件的输入(校验器)
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIntValidator,QDoubleValidator,QRegExpValidator
from PyQt5.QtCore import QRegExp
import sys

class QLineEditValidator(QWidget):
    def __init__(self):
        super(QLineEditValidator,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("校验器")
        #创建表单布局
        formLayout =QFormLayout()

        intLineEdit =QLineEdit()
        doubleLineEdit =QLineEdit()
        validatorLineEdit =QLineEdit()

        formLayout.addRow('整数类型', intLineEdit)
        formLayout.addRow('浮点类型', doubleLineEdit)
        formLayout.addRow('数字和字母',validatorLineEdit)

        intLineEdit.setPlaceholderText('整型')
        doubleLineEdit.setPlaceholderText('浮点型')
        validatorLineEdit.setPlaceholderText('字母和数字')

        #整数校验器[1,99]
        intValidator =QIntValidator(self)
        intValidator.setRange(1,99)

        #浮点校验器[-360,360],精度:小数点后两位
        doubleValidator =QDoubleValidator(self)
        doubleValidator.setRange(-360,360)
        doubleValidator.setNotation(QDoubleValidator.StandardNotation)
        #设置精度,小数点2位
        doubleValidator.setDecimals(2)

        #字符和数字
        reg = QRegExp('[a-zA-z0-9]+$')
        validator =QRegExpValidator(self)
        validator.setRegExp(reg)

        #设置校验器
        intLineEdit.setValidator(intValidator)
        doubleLineEdit.setValidator(doubleValidator)
        validatorLineEdit.setValidator(validator)

        self.setLayout(formLayout)

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QLineEditValidator()
   main.show()
   sys.exit(app.exec_())

代码7:# 用掩码限制QLineEdit控件的输入

from PyQt5.QtWidgets import *
import sys

class QLineEditMask(QWidget):
    def __init__(self):
        super(QLineEditMask,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('用掩码限制QLineEdit控件的输入')
        formLayout =QFormLayout()

        ipLineEdit = QLineEdit()
        macLineEdit =QLineEdit()
        dateLineEdit =QLineEdit()
        licenseLineEdit =QLineEdit()
        #192.168.21.45
        ipLineEdit.setInputMask('000.000.000.000;_')
        macLineEdit.setInputMask('HH:HH:HH:HH:HH:HH;_')
        dateLineEdit.setInputMask('0000-00-00')
        licenseLineEdit.setInputMask('>AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#')

        formLayout.addRow('数字掩码',ipLineEdit)
        formLayout.addRow('Mac掩饰',macLineEdit)
        formLayout.addRow('日期掩码',dateLineEdit)
        formLayout.addRow('许可证掩码',licenseLineEdit)

        self.setLayout(formLayout)
if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QLineEditMask()
   main.show()
   sys.exit(app.exec_())


代码8:综合案例(文本数据框)
# 综合案列

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
import sys

class QLineEditDemo(QWidget):
    def __init__(self):
        super(QLineEditDemo,self).__init__()
        self.initUI()


    def initUI(self):
        edit1 =QLineEdit()
        #使用int校验器
        edit1.setValidator(QIntValidator())
        edit1.setMaxLength(8) #不超过999999999
        edit1.setAlignment(Qt.AlignRight)
        edit1.setFont(QFont('Arial',20))


        edit2 =QLineEdit()
        edit2.setValidator(QDoubleValidator(0.99,99.99,2))

        edit3 =QLineEdit()
        edit3.setInputMask('99_9999_999999;#')

        edit4 =QLineEdit()
        edit4.textChanged.connect(self.textChanged)

        edit5 =QLineEdit()
        edit5.setEchoMode(QLineEdit.Password)
        edit5.editingFinished.connect(self.enterPress)

        edit6 =QLineEdit('hello PyQt5')
        edit6.setReadOnly((True))

        formLayout =QFormLayout()
        formLayout.addRow('整数校验',edit1)
        formLayout.addRow('浮点数校验', edit2)
        formLayout.addRow('Input Mask', edit3)
        formLayout.addRow('文本变化',edit4)
        formLayout.addRow('密码', edit5)
        formLayout.addRow('只读', edit6)

        self.setLayout(formLayout)
        self.setWindowTitle('QLineEdit综合案例')
    def textChanged(self,text):
        print('输入内容:'+text)
    def enterPress(self):
        print('已输入值')

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QLineEditDemo()
   main.show()
   sys.exit(app.exec_())


代码9:
# QTextEdit控件,输入多行文本,改变颜色,以及尺寸等
from PyQt5.QtWidgets import *
import sys

class QTextEditDemo(QWidget):
    def __init__(self):
        super(QTextEditDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('QTextEdit控件演示')

        self.resize(300,320)#修改尺寸

        self.textEdit = QTextEdit()
        self.buttonText = QPushButton('显示文本')
        self.buttonHTML =QPushButton('显示HTML')

        self.buttonToText = QPushButton('获取文本')
        self.buttonToHTML = QPushButton('获取HTML')

        layout =QVBoxLayout()
        layout.addWidget(self.textEdit)
        layout.addWidget(self.buttonText)
        layout.addWidget(self.buttonToText)
        layout.addWidget(self.buttonHTML)
        layout.addWidget(self.buttonToHTML)

        self.setLayout(layout)


        self.buttonText.clicked.connect(self.onClick_ButtonText)
        self.buttonHTML.clicked.connect(self.onClick_ButtonHTML)
        self.buttonToText.clicked.connect(self.onClick_ButtonToText)
        self.buttonToHTML.clicked.connect(self.onClick_ButtonToHTML)

    def onClick_ButtonText(self):
        self.textEdit.setPlainText('Hello World?')
    def onClick_ButtonToText(self):
        print(self.textEdit.toPlainText())
    def onClick_ButtonHTML(self):
        self.textEdit.setHtml('hello World')
    def onClick_ButtonToHTML(self):
        print(self.textEdit.toHtml())


if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QTextEditDemo()
   main.show()
   sys.exit(app.exec_())

代码10:按钮(*******用的上)
'''
按钮控件(QPushButton)
 QAbstractButton

 QPushButton 普通按钮
 AToolButton
 QRadioButton
 QCheckBox
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QPushButtonDemo(QDialog):
    def __init__(self):
        super(QPushButtonDemo,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('QPushnButton Demo')

        layout =QVBoxLayout()

        self.button1 =QPushButton('第一个按钮')
        self.button1.setText('first Button1')
        self.button1.setCheckable(True)
        self.button1.toggle()
        self.button1.clicked.connect(self.buttonState)
        self.button1.clicked.connect(lambda: self.whichButton(self.button1))

        layout.addWidget(self.button1)

        #在文本前面显示图像
        self.button2 =QPushButton('图像按钮')
        self.button2.setIcon(QIcon(QPixmap('E:/555/555/mydata3/train/images/001989.jpg')))
        self.button2.clicked.connect(lambda:self.whichButton(self.button2))
        layout.addWidget(self.button2)

        self.button3 =QPushButton('不可用的按钮')
        self.button3.setEnabled(False)
        layout.addWidget(self.button3)

        self.button4 =QPushButton('&MyButton')
        self.button4.setDefault(True)
        self.button4.clicked.connect(lambda:self.whichButton(self.button4))
        layout.addWidget(self.button4)


        self.setLayout(layout)
        self.resize(400,300)

    def buttonState(self):
        if self.button1.isChecked():
            print('按钮1已经被选中')
        else:
             print('按钮1未被选中')
    def whichButton(self,btn):
        print('被单击的按钮是<' + btn.text() + '>')

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QPushButtonDemo()
   main.show()
   sys.exit(app.exec_())

代码11:
'''
单选按钮控件(QRadioButton)
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QRadioButtonDemo(QWidget):
    def __init__(self):
        super(QRadioButtonDemo,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('QRadioButton')
        layout =QHBoxLayout()
        self.button1 = QRadioButton('单选按钮1')
        self.button1.setChecked(True)

        self.button1.toggled.connect(self.buttonState)
        layout.addWidget(self.button1)

        self.button2 =QRadioButton('单选按钮2')
        self.button2.toggled.connect(self.buttonState)
        layout.addWidget(self.button2)
        self.setLayout(layout)

    def buttonState(self):
        radioButton =self.sender()
        if radioButton.text() =='单选按钮1':
            if radioButton.isChecked() ==True:
                print('<' +radioButton.text()+ '>被选中')
            else:
                print('<'+radioButton.text() + '>被取消选中状态')
        if radioButton.text() =='单选按钮2':
            if radioButton.isChecked() ==True:
                print('<' +radioButton.text()+ '>被选中')
            else:
                print('<'+radioButton.text() + '>被取消选中状态')
if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QRadioButtonDemo()
   main.show()
   sys.exit(app.exec_())


代码12:
'''
复选框控件(QCheckBox)
即:可以同时选中多个按钮

3种状态
未选中:0
半选中:1
选中:2

'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

class QCheckBoxDemo(QWidget):
    def __init__(self):
        super(QCheckBoxDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('复选框控件演示')

        layout = QHBoxLayout()

        self.checkBox1 =QCheckBox('复选框控件1')
        self.checkBox1.setChecked(True)
        self.checkBox1.stateChanged.connect(lambda:self.checkboxState(self.checkBox1))
        layout.addWidget(self.checkBox1)

        self.checkBox2 = QCheckBox('复选框控件2')
        self.checkBox2.stateChanged.connect(lambda: self.checkboxState(self.checkBox2))
        layout.addWidget(self.checkBox2)

        self.checkBox3 = QCheckBox('半选中')
        self.checkBox3.stateChanged.connect(lambda: self.checkboxState(self.checkBox3))
        self.checkBox3.setTristate(True)
        self.checkBox3.setCheckState(Qt.PartiallyChecked)
        layout.addWidget(self.checkBox3)


        self.setLayout(layout)

    def checkboxState(self,cb):
        check1Status =self.checkBox1.text() + ', isChecked='+ str(self.checkBox1.isChecked()) +',checkState='+str(self.checkBox1.checkState())+'\n'
        check2Status =self.checkBox2.text() + ', isChecked='+ str(self.checkBox2.isChecked()) +',checkState='+str(self.checkBox2.checkState())+'\n'
        check3Status =self.checkBox3.text() + ', isChecked=' + str(self.checkBox3.isChecked()) + ',checkState=' + str(self.checkBox3.checkState()) + '\n'
        print(check1Status +check2Status +check3Status)

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QCheckBoxDemo()
   main.show()
   sys.exit(app.exec_())

代码13:
'''
下拉列表控件(QComboBox)
1.如果将列表项添加到QComboBox空间中
2.如何获取选中的列表项
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

class QComboBoxDemo(QWidget):
    def __init__(self):
        super(QComboBoxDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('下拉列表控件表示')
        self.resize(300,100)

        layout =QVBoxLayout()

        self.label =QLabel('请选择编程语言')

        self.cb =QComboBox()
        self.cb.addItem('C++')
        self.cb.addItem('ptthon')
        self.cb.addItems(['Java','C#','Ruby'])

        self.cb.currentIndexChanged.connect(self.selectionChange)

        layout.addWidget(self.label)
        layout.addWidget(self.cb)

        self.setLayout(layout)

    def selectionChange(self,i):
        self.label.setText(self.cb.currentText())
        self.label.adjustSize()

        for count in range(self.cb.count()):
            print('item' +str(count)+'='+ self.cb.itemText(count))
            print('current index',i,'selection changed',self.cb.currentText())

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QComboBoxDemo()
   main.show()
   sys.exit(app.exec_())


代码14:
'''
滑块控件(QSlider)

通过滑块设置字体大小
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

class QSliderDemo(QWidget):
    def __init__(self):
        super(QSliderDemo,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('滑块控件演示')
        self.resize(300,100)

        layout =QVBoxLayout()
        self.label =QLabel('你好 pyqt5')
        self.label.setAlignment(Qt.AlignCenter)

        layout.addWidget(self.label)
        self.slider =QSlider(Qt.Horizontal)

        #设置最小值
        self.slider.setMinimum(12)

        #设置最大值
        self.slider.setMaximum(48)

        #步长
        self.slider.setSingleStep(3)

        #设置当前值
        self.slider.setValue(18)

        #设置刻度的位置,刻度在下方
        self.slider.setTickPosition(QSlider.TicksBelow)

        #设置刻度的间隔
        self.slider.setTickInterval(6)

        layout.addWidget(self.slider)
        self.slider.valueChanged.connect(self.valueChange)
        self.setLayout(layout)

    def valueChange(self):
        print('当前值:%s' % self.slider.value())
        size =self.slider.value()
        self.label.setFont(QFont('Arial',size))

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QSliderDemo()
   main.show()
   sys.exit(app.exec_())


代码15:
'''
滑块控件(QSlider)

通过滑块设置字体大小
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

class QSliderDemo(QWidget):
    def __init__(self):
        super(QSliderDemo,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('滑块控件演示')
        self.resize(300,100)

        layout =QVBoxLayout()
        self.label =QLabel('你好 pyqt5')
        self.label.setAlignment(Qt.AlignCenter)

        layout.addWidget(self.label)

        self.slider =QSlider(Qt.Horizontal)


        #设置最小值
        self.slider.setMinimum(12)

        #设置最大值
        self.slider.setMaximum(48)

        #步长
        self.slider.setSingleStep(3)

        #设置当前值
        self.slider.setValue(18)

        #设置刻度的位置,刻度在下方
        self.slider.setTickPosition(QSlider.TicksBelow)

        #设置刻度的间隔
        self.slider.setTickInterval(6)

        layout.addWidget(self.slider)
        self.slider.valueChanged.connect(self.valueChange)

        self.slider1 =QSlider()

        self.setLayout(layout)

    def valueChange(self):
        print('当前值:%s' % self.slider.value())
        size =self.slider.value()
        self.label.setFont(QFont('Arial',size))

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QSliderDemo()
   main.show()
   sys.exit(app.exec_())


代码16:计数器控件
'''
计数器控件(QSpinBox)
控制数字的增加与减少,显示数字,捕获数字
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

class QSpinBoxDemo(QWidget):
    def __init__(self):
        super(QSpinBoxDemo,self).__init__()
        self.initUI()
    def initUI(self):
       self.setWindowTitle('QSpinBox演示')
       self.resize(300,100)

       layout =QVBoxLayout()
       self.label = QLabel('当前值')
       self.label.setAlignment(Qt.AlignCenter)

       layout.addWidget(self.label)

       self.sb = QSpinBox()
       self.sb.setValue(0)#默认值为0
       self.sb.setRange(10,38)
       self.sb.setSingleStep(3)#每间隔三个数字计数一次
       layout.addWidget(self.sb)
       self.sb.valueChanged.connect(self.valueChange)
       self.setLayout(layout)

    def valueChange(self):
        self.label.setText('当前值:' +str(self.sb.value()))
if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QSpinBoxDemo()
   main.show()
   sys.exit(app.exec_())

代码17:对话框

'''
对话框:QDialog

QMessageBox
QColorDialog
QFileDialog
QFontDialog
QInputDialog

QMainWindow/Qwidget/QDialog
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class QDialogDemo(QMainWindow):
    def __init__(self):
        super(QDialogDemo,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('QDialog案例')
        self.resize(300,200)

        self.button =QPushButton(self)
        self.button.setText('弹出对话框')
        self.button.move(50,50)
        self.button.clicked.connect(self.showDialog)

    def showDialog(self):
        dialog =QDialog()
        button =QPushButton('确定',dialog)
        button.clicked.connect(dialog.close)
        button.move(50,50)
        dialog.setWindowTitle('对话框')
        dialog.setWindowModality(Qt.ApplicationModal)
        dialog.exec()

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QDialogDemo()
   main.show()
   sys.exit(app.exec_())

代码17:消息对话框
'''
消息对话框:QMessageBox

1.关于对话框
2.错误对话框
3.警告对话框
4,提问对话框
5.消息对话框

有2点差异
1.显示的对话框图标可能不同。2.显示的按钮是不一样的
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QMessageBoxDemo(QWidget):
    def __init__(self):
        super(QMessageBoxDemo,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('QMessageBox案例')
        self.resize(300,400)

        layout =QVBoxLayout()

        self.button1 =QPushButton()
        self.button1.setText('显示关于对话框')
        self.button1.clicked.connect(self.showDialog)

        self.button2 =QPushButton()
        self.button2.setText('显示消息对话框')
        self.button2.clicked.connect(self.showDialog)

        self.button3 = QPushButton()
        self.button3.setText('显示警告对话框')
        self.button3.clicked.connect(self.showDialog)

        self.button4 = QPushButton()
        self.button4.setText('显示错误对话框')
        self.button4.clicked.connect(self.showDialog)

        self.button5 = QPushButton()
        self.button5.setText('显示提问对话框')
        self.button5.clicked.connect(self.showDialog)


        layout.addWidget(self.button1)
        layout.addWidget(self.button2)
        layout.addWidget(self.button3)
        layout.addWidget(self.button4)
        layout.addWidget(self.button5)

        self.setLayout(layout)

    def showDialog(self):
        text =self.sender().text()
        if text =='显示关于对话框':
            QMessageBox.about(self,'关于','这是一个关于对话框')
        elif text =='显示消息对话框':
            reply =QMessageBox.information(self,'消息','这是一个消息对话框',QMessageBox.Yes |QMessageBox.No,QMessageBox.Yes)
            print(reply)
        elif text =='显示警告对话框':
            QMessageBox.warning(self,'警告','这是一个警告对话框',QMessageBox.Yes |QMessageBox.No,QMessageBox.Yes)
        elif text =='显示错误对话框':
            QMessageBox.critical(self,'错误','这是一个错误对话框',QMessageBox.Yes |QMessageBox.No,QMessageBox.Yes)
        elif text =='显示提问对话框':
            QMessageBox.question(self,'错误','这是一个提问对话框',QMessageBox.Yes |QMessageBox.No,QMessageBox.Yes)

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QMessageBoxDemo()
   main.show()
   sys.exit(app.exec_())


代码18:
'''
输入对话框:QInputDialog

QInputDialog.getItem
QInputDialog.getText
QInputDialog.getInt

'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QInputDialogDemo(QWidget):
    def __init__(self):
        super(QInputDialogDemo,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle('输入对话框')
        layout =QFormLayout()

        self.button1 =QPushButton('获取列表中的选项')
        self.button1.clicked.connect(self.getItem)
        self.lineEdit1 =QLineEdit()
        layout.addRow(self.button1,self.lineEdit1)

        self.button2 = QPushButton('获取字符串')
        self.button2.clicked.connect(self.getText)
        self.lineEdit2 = QLineEdit()
        layout.addRow(self.button2, self.lineEdit2)

        self.button3 = QPushButton('获取整数')
        self.button3.clicked.connect(self.getInt)
        self.lineEdit3 = QLineEdit()
        layout.addRow(self.button3, self.lineEdit3)

        self.setLayout(layout)
    def getItem(self):
        items =('C','C++','Ruby','Python','Java')
        item,ok =QInputDialog.getItem(self,'请输入编程语言','语言列表',items)
        if ok and item:
            self.lineEdit1.setText(item)
    def getText(self):
        text,ok =QInputDialog.getText(self,'文本输入框','输入姓名')
        if ok and text:
            self.lineEdit2.setText(text)
    def getInt(self):
        num,ok =QInputDialog.getInt(self,'整数输入框','输入数字')
        if ok and num:
            self.lineEdit3.setText(str(num))

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QInputDialogDemo()
   main.show()
   sys.exit(app.exec_())


代码19:
'''
字体对话框:QFontDialog,就是字体设置的那里
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QFontDialogDemo(QWidget):
    def __init__(self):
        super(QFontDialogDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Font Dialog例子')
        layout =QVBoxLayout()
        self.fontButton =QPushButton('选择字体')
        self.fontButton.clicked.connect(self.getFont)
        layout.addWidget(self.fontButton)

        self.fontLabel =QLabel('Hello, 测试字体例子')
        layout.addWidget(self.fontLabel)
        self.setLayout(layout)
    def getFont(self):
        font,ok =QFontDialog.getFont()
        if ok:
            self.fontLabel.setFont(font)


if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QFontDialogDemo()
   main.show()
   sys.exit(app.exec_())


代码20:
'''
颜色对话框:QColorDialog
'''

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QColorDialogDemo(QWidget):
    def __init__(self):
        super(QColorDialogDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Color Dialog例子')
        layout =QVBoxLayout()

        self.colorButton =QPushButton('设置字体颜色')
        self.colorButton.clicked.connect(self.getColor)
        layout.addWidget(self.colorButton)

        self.colorButton1 = QPushButton('设置背景颜色')
        self.colorButton1.clicked.connect(self.getBGColor)
        layout.addWidget(self.colorButton1)


        self.colorLabel =QLabel('Hello, 测试yanse例子')
        layout.addWidget(self.colorLabel)
        self.setLayout(layout)

    def getColor(self):
        color =QColorDialog.getColor()
        p =QPalette()
        p.setColor(QPalette.WindowText,color)
        self.colorLabel.setPalette(p)
    def getBGColor(self):
        color =QColorDialog.getColor()
        p =QPalette()
        p.setColor(QPalette.Window,color)
        self.colorLabel.setAutoFillBackground(True)
        self.colorLabel.setPalette(p)

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QColorDialogDemo()
   main.show()
   sys.exit(app.exec_())


代码21:加载图片以及txt文本
'''
文件对话框:QFileDialog
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class QFileDialogDemo(QWidget):
    def __init__(self):
        super(QFileDialogDemo,self).__init__()
        self.initUI()

    def initUI(self):
        layout =QVBoxLayout()
        self.button1 =QPushButton('加载图片')
        self.button1.clicked.connect(self.loadImage)
        layout.addWidget(self.button1)

        self.imageLabel =QLabel()
        layout.addWidget(self.imageLabel)

        self.button2 =QPushButton('加载文本文件')
        self.button2.clicked.connect(self.loadText)
        layout.addWidget(self.button2)

        self.contents =QTextEdit()
        layout.addWidget(self.contents)

        self.setLayout(layout)
        self.setWindowTitle('文件对话框演示')

    def loadImage(self):
        fname,_ = QFileDialog.getOpenFileName(self,'打开文件','.','图像文件(*.jpg *.png)')
        self.imageLabel.setPixmap(QPixmap(fname))
    def loadText(self):
        dialog =QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setFilter(QDir.Files)
        if dialog.exec():
            filenames =dialog.selectedFiles()
            f =open(filenames[0],encoding ='utf-8',mode='r')
            with f:
                 data =f.read()
                 self.contents.setText(data)


if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =QFileDialogDemo()
   main.show()
   sys.exit(app.exec_())


代码22:
'''
绘制API: 绘制文本
1.文本
2,各种图形(直线,点,椭圆)
3.图像

QPainter
painter =QPainter()
painter.begin()
painter.drawText()
painter.end
必须在paintEvent事件方法中绘制各种元素
'''

import sys
from PyQt5.QtWidgets import QApplication,QWidget
from PyQt5.QtGui import QPainter,QColor,QFont
from PyQt5.QtCore import Qt

class DrawText(QWidget):
    def __init__(self):
        super(DrawText,self).__init__()
        self.setWindowTitle('在窗口上绘制文本')
        self.resize(300,200)
        self.text ="Python菜鸟"
    def paintEvent(self, event):
        painter =QPainter(self)
        painter.begin(self)
        print("aaa")

        painter.setPen(QColor(150,43,5))
        painter.setFont(QFont('SimSun',25))

        painter.drawText(event.rect(),Qt.AlignCenter,self.text)
        painter.end()

if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =DrawText()
   main.show()
   sys.exit(app.exec_())


代码23:
'''
用像素点绘制正弦曲线
-2pi  2pi
drawPoint(x,y)
'''

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt

class DrawPoints(QWidget):
    def __init__(self):
        super(DrawPoints,self).__init__()
        self.resize(300,300)
        self.setWindowTitle('在窗口上用像素点绘制2个周期的正弦曲线')
    def paintEvent(self,enent):
        painter =QPainter()
        painter.begin(self)
        painter.setPen(Qt.blue)
        size =self.size()

        for i in range(1000):
            x =100*(-1+2.0*i/1000)+ size.width()/2.0
            y =-50*math.sin((x -size.width()/2.0)*math.pi/50)+size.height()/2.0
            painter.drawPoint(x,y)
        painter.end()
        
if __name__ =='__main__':
   app =QApplication(sys.argv)
   main =DrawPoints()
   main.show()
   sys.exit(app.exec_())


代码24:

'''
绘制不同样式的直线(虚线、点划线)

'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt


class DraeMultiLine(QWidget):
    def __init__(self):
        super(DraeMultiLine, self).__init__()
        self.resize(300, 300)
        self.setWindowTitle('设置Pen的样式')

    def paintEvent(self, enent):
        painter = QPainter()
        painter.begin(self)
        painter.setPen(Qt.blue)

        pen =QPen(Qt.red,3,Qt.SolidLine)

        painter.setPen(pen)#实线
        painter.drawLine(20,40,250,40)

        pen.setStyle(Qt.DashLine)#虚线
        painter.drawLine(20,80,250,80)

        pen.setStyle(Qt.DashDotLine)  # 点划线
        painter.setPen(pen)
        painter.drawLine(20, 120, 250, 120)

        pen.setStyle(Qt.DotLine)  # 点线
        painter.setPen(pen)
        painter.drawLine(20, 160, 250, 160)

        pen.setStyle(Qt.DashDotDotLine)  # 点划线
        painter.setPen(pen)
        painter.drawLine(20, 200, 250, 200)

        pen.setStyle(Qt.CustomDashLine)  # 自定义线性
        pen.setDashPattern([1,10,5,4])
        painter.setPen(pen)
        painter.drawLine(20, 240, 250, 240)

        size = self.size()

        painter.end()
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = DraeMultiLine()
    main.show()
    sys.exit(app.exec_())


代码25:
'''
绘制各种图形(圆弧,圆形,椭圆,矩形(正方形),多边形,绘制图像)
'''

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class DrawAll(QWidget):
    def __init__(self):
        super(DrawAll, self).__init__()
        self.resize(300, 600)
        self.setWindowTitle('绘制各种图形')
    def paintEvent(self, event):
        qp =QPainter()
        qp.begin(self)

        qp.setPen(Qt.blue)

        #绘制圆弧
        rect =QRect(0,10,100,100)#确定区域
        qp.drawArc(rect,0,50*16)#alen:1个alen等于1/16度  45度 =45*16,例如绘制50度

        qp.setPen(Qt.red)#通过圆弧绘制圆,采用红色
        qp.drawArc(120,10,100,100,0,360*16)

        #绘制带弦的圆弧
        qp.drawChord(10,120,100,100,12,130*16)

        #绘制扇形
        qp.drawPie(10,240,100,100,12,130*16)

        #绘制椭圆
        qp.drawEllipse(120,120,150,100)

        # 绘制多边形,例如绘制五边形
        point1 = QPoint(140, 380)
        point2 = QPoint(270, 420)
        point3 = QPoint(290, 512)
        point4 = QPoint(100, 100)
        point5 = QPoint(200, 200)
        polyon = QPolygon([point1, point2, point3, point4, point5])
        qp.drawPolygon(polyon)

        #绘制图像
        image =QImage('E:/555/555/mydata3/train/images/001995.jpg')
        rect =QRect(10,400,image.width()/3,image.height()/3)#绘制区域选定
        qp.drawImage(rect,image)#绘制图像

        qp.end()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = DrawAll()
    main.show()
    sys.exit(app.exec_())


代码26:

'''
用画刷填充图形区域(横格、斜格)

'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class FillRect(QWidget):
    def __init__(self):
        super(FillRect, self).__init__()
        self.resize(600, 600)
        self.setWindowTitle('用画刷填充区域')
    def paintEvent(self,e):
        qp =QPainter()
        qp.begin(self)

        brush =QBrush(Qt.SolidPattern)
        qp.setBrush(brush)
        qp.drawRect(10,15,90,60)

        brush = QBrush(Qt.Dense1Pattern)
        qp.setBrush(brush)
        qp.drawRect(130, 15, 90, 60)

        brush = QBrush(Qt.Dense2Pattern)
        qp.setBrush(brush)
        qp.drawRect(250, 15, 90, 60)

        brush = QBrush(Qt.Dense3Pattern)
        qp.setBrush(brush)
        qp.drawRect(10, 105, 90, 60)

        brush = QBrush(Qt.HorPattern)
        qp.setBrush(brush)
        qp.drawRect(130, 105, 90, 60)

        qp.end()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = FillRect()
    main.show()
    sys.exit(app.exec_())


代码27:
'''
让控件支持拖拽动作:例如A拖拽至B
A
B. setAcceptDrops(True)
B需要两个事件:1.dragEnterEvent(将A拖到B 触发)
               2.dropEvent (在B的区域放下A时触发)
'''

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MyComboBox(QComboBox):
    def __init__(self):
        super(MyComboBox,self).__init__()
        self.setAcceptDrops(True)

    def dragEnterEvent(self,e):
        print(e)
        if e.minmeData().hasText():
            e.accept()
        else:
            e.ignore()
    def dropEvent(self,e):
        self.addItem(e.mimeData().text())

class DrapDropDemo(QWidget):
    def __init__(self):
        super(DrapDropDemo,self).__init__()
        formLayout =QFormLayout()
        formLayout.addRow(QLabel("请将左边的文本拖拽到右边的下拉列表中"))
        lineEdit =QLineEdit()
        lineEdit.setDragEnabled(True)#让QLineEdit控件可拖动

        combo =MyComboBox()
        formLayout.addRow(lineEdit,combo)
        self.setLayout(formLayout)
        self.setWindowTitle('拖拽案例')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MyComboBox()
    main.show()
    sys.exit(app.exec_())


代码28:

'''
使用剪贴板

共享数据
'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ClipBoard(QDialog):
    def __init__(self):
        super(ClipBoard,self).__init__()
        textCopyButton =QPushButton('复制文本')
        textPasteButton =QPushButton('粘贴文本')

        htmlCopyButton =QPushButton('复制HTML')
        htmlPasteButton = QPushButton('粘贴HTML')

        imageCopyButton =QPushButton('复制图像')
        imagePasteButton =QPushButton('粘贴图像')

        self.textLabel =QLabel('默认文本')
        self.imageLabel =QLabel()
        self.imageLabel.setPixmap(QPixmap('E:/555/555/mydata3/train/images/001994.jpg'))

        layout =QGridLayout()
        layout.addWidget(textCopyButton,0,0)
        layout.addWidget(imageCopyButton, 0, 1)
        layout.addWidget(htmlCopyButton, 0, 2)
        layout.addWidget(textPasteButton, 1, 0)
        layout.addWidget(htmlPasteButton, 1, 1)
        layout.addWidget(imagePasteButton, 1, 2)

        layout.addWidget(self.textLabel,2,0,1,2)
        layout.addWidget(self.imageLabel,2,2)

        self.setLayout(layout)

        textCopyButton.clicked.connect(self.copyText)
        textPasteButton.clicked.connect(self.pasteText)
        htmlCopyButton.clicked.connect(self.copyHtml)
        htmlPasteButton.clicked.connect(self.pasteHtml)
        imageCopyButton.clicked.connect(self.copyImage)
        imagePasteButton.clicked.connect(self.pasteImage)

        self.setWindowTitle('剪贴板演示')

    def copyText(self):
        clipboard =QApplication.clipboard()
        clipboard.setText('hello word')
    def pasteText(self):
        clipboard = QApplication.clipboard()
        self.textLabel.setText(clipboard.text())

    def copyImage(self):
        clipboard =QApplication.clipboard()
        clipboard.setPixmap(QPixmap('E:/555/555/mydata3/train/images/001994.jpg'))

    def pasteImage(self):
        clipboard =QApplication.clipboard()
        self.imageLabel.setPixmap(clipboard.pixmap())

    def copyHtml(self):
        mimeData =QMimeData()
        mimeData.setHtml('Bold and Red')
        clipboard =QApplication.clipboard()
        clipboard.setMineData(mimeData)

    def pasteHtml(self):
        clipboard =QApplication.clipboard()
        mimeData =clipboard.mimeData()
        if mimeData.hasHtml():
            self.textLabel.setText(mimeData.Html())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = ClipBoard()
    main.show()
    sys.exit(app.exec_())

代码29:
'''
日历控件
QCalendarWidget
'''

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class MyCalendar(QWidget):
    def __init__(self):
        super(MyCalendar,self).__init__()
        self.initUI()
    def initUI(self):
        self.cal =QCalendarWidget(self)
        self.cal.setMinimumDate(QDate(1998,1,1))
        self.cal.setMaximumDate(QDate(2088,1,1))

        self.cal.setGridVisible(True)
        self.cal.move(20,20)

        self.cal.clicked.connect(self.showDate)
        self.label =QLabel(self)
        date =self.cal.selectedDate()
        self.label.setText(date.toString("yyyy-MM-dd dddd"))
        self.label.move(20,300)

        self.resize(400,350)
        self.setWindowTitle("日历演示")

    def showDate(self,date):
        self.label.setText(date.toString("yyyy-MM-dd dddd"))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MyCalendar()
    main.show()
    sys.exit(app.exec_())


代码30:各种风格的日期和时间

'''
输入各种风格的日期和时间
QDateTimeEdit
'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class DateTimeEdit1(QWidget):
    def __init__(self):
        super(DateTimeEdit1,self).__init__()
        self.initUI()
    def initUI(self):

        vlayout =QVBoxLayout()
        dateTimeEdit1 =QDateTimeEdit()
        dateTimeEdit2 =QDateTimeEdit(QDateTime.currentDateTime())

        dateEdit =QDateTimeEdit(QDate.currentDate())
        timeEdit =QDateTimeEdit(QTime.currentTime())

        dateTimeEdit1.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        dateTimeEdit2.setDisplayFormat("yyyy-MM-dd HH:mm:ss")

        dateEdit.setDisplayFormat("yyyy.MM.dd")
        timeEdit.setDisplayFormat("HH:mm:ss")

        vlayout.addWidget(dateTimeEdit1)
        vlayout.addWidget(dateTimeEdit2)
        vlayout.addWidget(dateEdit)
        vlayout.addWidget(timeEdit)
        self.setLayout(vlayout)

        self.resize(300,90)
        self.setWindowTitle("设置不同风格的日期和时间")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = DateTimeEdit1()
    main.show()
    sys.exit(app.exec_())


代码31:
'''
输入各种风格的日期和时间
QDateTimeEdit
'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class DateTimeEdit1(QWidget):
    def __init__(self):
        super(DateTimeEdit1,self).__init__()
        self.initUI()
    def initUI(self):

        vlayout =QVBoxLayout()
        dateTimeEdit1 =QDateTimeEdit()
        dateTimeEdit2 =QDateTimeEdit(QDateTime.currentDateTime())
        dateTimeEdit1.setMinimumDate(QDate.currentDate().addDays(-365))
        dateTimeEdit1.setMinimumDate(QDate.currentDate().addDays(365))
        self.dateTimeEdit =dateTimeEdit1
        dateTimeEdit2.setCalendarPopup(True)

        dateEdit =QDateTimeEdit(QDate.currentDate())
        timeEdit =QDateTimeEdit(QTime.currentTime())

        dateTimeEdit1.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        dateTimeEdit2.setDisplayFormat("yyyy-MM-dd HH:mm:ss")

        dateEdit.setDisplayFormat("yyyy.MM.dd")
        timeEdit.setDisplayFormat("HH:mm:ss")

        dateTimeEdit1.dateChanged.connect(self.onDateChanged)
        dateTimeEdit1.timeChanged.connect(self.onTimeChanged)
        dateTimeEdit1.dateTimeChanged.connect(self.onDateTimeChanged)


        vlayout.addWidget(dateTimeEdit1)
        vlayout.addWidget(dateTimeEdit2)
        vlayout.addWidget(dateEdit)
        vlayout.addWidget(timeEdit)

        self.btn =QPushButton('获取日期和时间')
        self.btn.clicked.connect(self.onButtonClick)
        vlayout.addWidget(self.btn)

        self.setLayout(vlayout)

        self.resize(300,90)
        self.setWindowTitle("设置不同风格的日期和时间")

    #日期变化
    def onDateChanged(self,date):
        print(date)
    #时间变化
    def onTimeChanged(self,time):
        print(time)

    #时间和日期变化
    def onDateTimeChanged(self,datetime):
        print(datetime)

    def onButtonClick(self):
        datetime =self.dateTimeEdit.dateTime()
        print(datetime)

        #最大日期
        print(self.dateTimeEdit.maximumDate())

        #最大日期和时间
        print(self.dateTimeEdit.maximumDateTime())

        # 最小日期
        print(self.dateTimeEdit.minimumDateTime())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = DateTimeEdit1()
    main.show()
    sys.exit(app.exec_())


代码32:

'''
创建和使用菜单
'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class Menu(QMainWindow):
    def __init__(self):
        super(Menu,self).__init__()
        bar =self.menuBar()#创建菜单栏

        file =bar.addMenu('文件')
        file.addAction('新建')

        save =QAction("保存",self)
        save.setShortcut("ctrl + S")
        file.addAction(save)

        save.triggered.connect(self.process)

        edit =bar.addMenu("Edit")
        edit.addAction("copy")
        edit.addAction("paste")
        quit =QAction("Quit",self)
        file.addAction(quit)


    def process(self,a):
        print(a.sneder().text())

if __name__ =='__main__':
    app =QApplication(sys.argv)
    main =Menu()
    main.show()
    sys.exit(app.exec_())


代码33:

'''
创建和使用工具栏并且添加按钮,
工具栏默认按钮:只显示图标,将文本作为悬停提示展示

工具栏按钮有3种属性:1.只显示图标。2.只显示文本。3.同时显示文本和图标。
'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class Toolbar(QMainWindow):
    def __init__(self):
        super(Toolbar,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle("工具栏创建例子")
        self.resize(300,200)

        tb1 =self.addToolBar("file")#添加工具栏按钮
        new =QAction(QIcon('E:/555/555/mydata3/train/images/000167.jpg'),"new",self)
        tb1.addAction(new)
        open =QAction(QIcon('E:/555/555/mydata3/train/images/000001.jpg'),"open",self)
        tb1.addAction(open)
        save =QAction(QIcon('E:/555/555/mydata3/train/images/000200.jpg'),"save",self)
        tb1.addAction(save)
         #显示文本也显示图标
        #tb1.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        tb2 =self.addToolBar("File1")
        new1 =QAction(QIcon('E:/555/555/mydata3/train/images/001000.jpg'),"新建",self)
        tb2.addAction(new1)
        tb2.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        tb1.actionTriggered.connect(self.toolbtnpressed)#触发tb1
        tb2.actionTriggered.connect(self.toolbtnpressed)#触发tb2

    def toolbtnpressed(self,a):
        print("按下的工具栏按钮是",a.text)

if __name__ =='__main__':
    app =QApplication(sys.argv)
    main =Toolbar()
    main.show()
    sys.exit(app.exec_())

代码34:
'''
创建和使用状态栏
'''

import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class StatusBar(QMainWindow):
    def __init__(self):
        super(StatusBar,self).__init__()
        self.initUI()
    def initUI(self):
        self.setWindowTitle("工具栏创建例子")
        self.resize(300,200)

        bar =self.menuBar()
        file =bar.addMenu('File')
        file.addAction("show")
        file.triggered.connect(self.processTrigger)

        #self.triggered.connect(self.processTrigger)
        self.setCentralWidget(QTextEdit())
        self.statusBar =QStatusBar()
        self.setStatusBar(self.statusBar)

    def processTrigger(self,q):
        if q.text()=="show":
            self.statusBar.showMessage(q.text()+ "菜单被点击了",5000)#状态显示5s

if __name__ =='__main__':
    app =QApplication(sys.argv)
    main =StatusBar()
    main.show()
    sys.exit(app.exec_())


代码35:
'''
将数据输出至传真机或者打印机
'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtGui,QtWidgets,QtPrintSupport

class PrintSupport(QMainWindow):
    def __init__(self):
        super(PrintSupport,self).__init__()
        self.setGeometry(500,200,300,300)
        self.button =QPushButton("打印QTextEdit控件中的内容",self)
        self.button.setGeometry(20,20,260,30)
        self.editor =QTextEdit('默认文本',self)
        self.editor.setGeometry(20,60,260,200)

        self.button.clicked.connect(self.print)

    def print(self):
        printer =QtPrintSupport.QPrinter()
        painter =QtGui.QPainter()
        #将绘制的额目标重定到打印机
        painter.begin(printer)
        screen =self.editor.grab()
        painter.drawPixmap(10,10,screen)
        painter.end()
        print("print")

if __name__ =='__main__':
    app =QApplication(sys.argv)
    main =PrintSupport()
    main.show()
    sys.exit(app.exec_())


代码36:
'''
显示打印对话框
'''
import sys, math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtGui,QtWidgets,QtPrintSupport
from PyQt5.QtPrintSupport import QPageSetupDialog,QPrintDialog,QPrinter

class PrintDialog(QMainWindow):
    def __init__(self):
        super(PrintDialog,self).__init__()
        self.printer = QPrinter()
        self.initUI()
    def initUI(self):
        self.setGeometry(300,300,500,400)
        self.setWindowTitle('打印对话框')

        self.editor = QTextEdit(self)
        self.editor.setGeometry(20,20,300,270)

        self.openButton = QPushButton('打开文件',self)
        self.openButton.move(350,20)

        self.settingsButton =QPushButton('打印设置',self)
        self.settingsButton.move(350,50)

        self.printButton =QPushButton('打印文档',self)
        self.printButton.move(350,80)

        self.openButton.clicked.connect(self.openFile)
        self.settingsButton.clicked.connect(self.showSettingDialog)
        self.printButton.clicked.connect(self.showPrintDialog)

    #打开文件
    def openFile(self):
        fname =QFileDialog.getOpenFileName(self,'打开文本文件','./')
        if fname[0]:
            with open(fname[0],'r',encoding='utf-8',errors ='ignore')as f:
                self.editor.setText(f.read())

    #显示打印设置对话框
    def showSettingDialog(self):
        printDialog =QPageSetupDialog(self.printer,self)
        printDialog =QPageSetupDialog(self.printer,self)
        printDialog.exec()

    #显示打印对话框
    def showPrintDialog(self):
        printdialog =QPrintDialog(self.printer,self)
        if QDialog.Accepted ==printdialog.exec():
            self.editor.print(self.printer)

if __name__ =='__main__':
    app =QApplication(sys.argv)
    main =PrintDialog()
    main.show()
    sys.exit(app.exec_())


代码37:

'''
显示二维表数据(QTableView控件)

显示表和图上的数据,需要提供数据源 Model
即:需要创建QTableView实例和一个数据源(Model),然后将两者关联

    MVC : Model Viewer Controller
    MVC的目的是将后端的数据和前段页面的耦合度降低
'''
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys

class TableView(QWidget):
    def __init__(self,arg =None):
        super(TableView,self).__init__(arg)
        self.setWindowTitle("QTableView表格视图控件演示")
        self.resize(500,300);

        #创建model和头部
        self.model =QStandardItemModel(4,3)
        self.model.setHorizontalHeaderLabels(['id','姓名','年龄'])


        self.tableview =QTableView()
        #并联QTableView控件和Model
        self.tableview.setModel(self.model)

        #添加数据
        item11 =QStandardItem('10')
        item12 = QStandardItem('雷神')
        item13 = QStandardItem('2000')
        self.model.setItem(0, 0, item11)
        self.model.setItem(0, 1, item12)
        self.model.setItem(0, 2, item13)

        item31 = QStandardItem('30')
        item32 = QStandardItem('zhanshen')
        item33 = QStandardItem('ok')
        self.model.setItem(2, 0, item31)
        self.model.setItem(2, 1, item32)
        self.model.setItem(2, 2, item33)

        layout =QVBoxLayout()
        layout.addWidget(self.tableview)
        self.setLayout(layout)

if __name__ =='__main__':
    app =QApplication(sys.argv)
    main =TableView()
    main.show()
    sys.exit(app.exec_())


代码38:
'''
显示列表数据(QListView控件)
'''
from PyQt5.QtWidgets import QApplication,QWidget,QVBoxLayout,QListView,QMessageBox
from PyQt5.QtCore import QStringListModel
import sys

class ListViewDemo(QWidget):
    def __init__(self,parent =None):
        super(ListViewDemo,self).__init__(parent)
        self.setWindowTitle("QListView例子")
        self.resize(300,270)
        layout =QVBoxLayout()

        listview =QListView()
        listModel =QStringListModel()
        self.list =["列表项1","列表项2","列表项3"]

        listModel.setStringList(self.list)

        listview.setModel(listModel)
        listview.clicked.connect(self.clicked)
        layout.addWidget(listview)

        self.setLayout(layout)

    def clicked(self,item):
        QMessageBox.information(self,"QListView","您选择了:"+self.list[item.row()])

if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =ListViewDemo()
    win.show()
    sys.exit(app.exec_())


代码39:
'''
扩展的列表控件(QListWidget)
'''

from PyQt5.QtWidgets import *
import sys

class ListWindgetDemo(QMainWindow):
    def __init__(self,parent =None):
        super(ListWindgetDemo,self).__init__(parent)
        self.setWindowTitle("QListView例子")
        self.resize(300,270)
        self.listwidget =QListWidget()
        #self.listwidget.resize(300,120)
        self.listwidget.addItem("item1")
        self.listwidget.addItem("item2")
        self.listwidget.addItem("item3")
        self.listwidget.addItem("item4")
        self.listwidget.addItem("item5")

        self.listwidget.itemClicked.connect(self.clicked)

        #self.listwidget.setWindowTitle("demo")

        self.setCentralWidget(self.listwidget)
    def clicked(self,Index):
        QMessageBox.information(self,"QListWidget","您选择了:" +self.listwidget.item(self.listwidget.row(Index)).text())

if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =ListWindgetDemo()
    win.show()
    sys.exit(app.exec_())

代码40:

'''
扩展的表格控件(QTableWidget)
每一个Cell(单元格)是一个QTableWidgetItem
'''

import sys
from PyQt5.QtWidgets import *

class TableWidgetDemo(QWidget):
    def __init__(self):
        super(TableWidgetDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget演示")
        self.resize(430,230)
        layout =QHBoxLayout()
        tablewidget =QTableWidget()
        tablewidget.setRowCount(4)
        tablewidget.setColumnCount(3)

        layout.addWidget(tablewidget)
        tablewidget.setHorizontalHeaderLabels(['姓名','年龄','籍贯'])

        nameItem =QTableWidgetItem("小明")
        tablewidget.setItem(0,0,nameItem)
        ageItem = QTableWidgetItem("25岁")
        tablewidget.setItem(0, 1, ageItem)
        jgItem = QTableWidgetItem("山东济南")
        tablewidget.setItem(0, 2, jgItem)

        tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers)#禁止编辑
        tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows)#整行选择

        #调整行和列
        tablewidget.resizeColumnsToContents()
        tablewidget.resizeRowsToContents()

        #隐藏表格线
        tablewidget.setShowGrid(False)

        self.setLayout(layout)


if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =TableWidgetDemo()
    win.show()
    sys.exit(app.exec_())

代码41:
'''
在单元格放置控件(例如放置下拉菜单)
'''

import sys
from PyQt5.QtWidgets import *

class PlaceControlInCell(QWidget):
    def __init__(self):
        super(PlaceControlInCell,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget演示")
        self.resize(430,300)
        layout =QHBoxLayout()
        tableWidget =QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)

        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(Kg)'])
        textItem =QTableWidgetItem('小明')
        tableWidget.setItem(0,0,textItem)

        combox =QComboBox()
        combox.addItem('男')
        combox.addItem('女')
        #QSS
        combox.setStyleSheet('QComboBox{margin:3px};')
        tableWidget.setCellWidget(0,1,combox)

        modifyButton =QPushButton('修改')
        modifyButton.setDown(True)
        modifyButton.setStyleSheet('QPushButton{margin:3px};')
        tableWidget.setCellWidget(0,2,modifyButton)

        self.setLayout(layout)


if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =PlaceControlInCell()
    win.show()
    sys.exit(app.exec_())

代码42:
'''
在表格中快速定位到特定的行
1.数据的定位
2.如果找到满足条件的单元格,会定位到单元格所在的行
'''

import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtGui import QColor,QBrush

class DataLocation(QWidget):
    def __init__(self):
        super(DataLocation,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("QTableWidget演示")
        self.resize(600,800);

        layout =QHBoxLayout()
        tableWidget =QTableWidget()
        tableWidget.setRowCount(40)
        tableWidget.setColumnCount(4)

        layout.addWidget(tableWidget)

        for i in range(40):
            for j in range(4):
                itemContent ='(%d,%d)'%(i,j)
                tableWidget.setItem(i,j,QTableWidgetItem(itemContent))
        self.setLayout(layout)
        #搜索满足条件的Cell(例如(13,1))
        text ='(13,1)'
        items =tableWidget.findItems(text,QtCore.Qt.MatchExactly)
        if len(items)>0:
            item =items[0]
            item.setBackground(QBrush(QColor(0,255,0)))#设置背景色
            item.setForeground(QBrush(QColor(255,0,0)))#设置匹配上内容的颜色

            row =item.row()

            #定位到指定的行
            tableWidget.verticalScrollBar().setSliderPosition(row)

if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =DataLocation()
    win.show()
    sys.exit(app.exec_())

代码43:
'''
设置单元格字体和颜色
'''

import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtGui import QColor,QBrush,QFont

class CellFontAndColor(QWidget):
    def __init__(self):
        super(CellFontAndColor,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("设置单元格字体和颜色")
        self.resize(430,230);
        layout =QHBoxLayout()
        tableWidget =QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])

        newItem =QTableWidgetItem('雷神')
        newItem.setFont(QFont('Times',14,QFont.Black))
        newItem.setForeground(QBrush(QColor(255,0,0)))#将颜色设置成红色
        tableWidget.setItem(0,0,newItem)

        newItem = QTableWidgetItem('死亡女神')
        newItem.setFont(QFont('Times', 14, QFont.Black))#设置字体大小
        newItem.setForeground(QBrush(QColor(255, 255, 0)))  # 将颜色设置成红色
        newItem.setBackground(QBrush(QColor(0,0,255)))#设置背景颜色
        tableWidget.setItem(0, 1, newItem)
        

        newItem = QTableWidgetItem('110')
        newItem.setFont(QFont('Times', 20, QFont.Black))  # 设置字体大小
        newItem.setForeground(QBrush(QColor(255, 255, 0)))  # 将颜色设置成红色
        newItem.setBackground(QBrush(QColor(0, 0, 255)))  # 设置背景颜色
        tableWidget.setItem(0, 2, newItem)

        self.setLayout(layout)

if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =CellFontAndColor()
    win.show()
    sys.exit(app.exec_())


代码44:
'''
按序排列
1.按哪一列排序
2.排序类型:升序或降序

sortItems(colimnIndex,orderTppe)
'''

import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtGui import QColor,QBrush,QFont
from PyQt5.QtCore import *


class ColunSort(QWidget):
    def __init__(self):
        super(ColunSort,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("按列排序")
        self.resize(430,230);
        layout =QHBoxLayout()
        self.tableWidget =QTableWidget()
        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(3)
        layout.addWidget(self.tableWidget)

        self.tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])

        newItem =QTableWidgetItem('张三')
        self.tableWidget.setItem(0,0,newItem)
        newItem = QTableWidgetItem('男')
        self.tableWidget.setItem(0, 1, newItem)
        newItem = QTableWidgetItem('165')
        self.tableWidget.setItem(0, 2, newItem)

        newItem = QTableWidgetItem('李四')
        self.tableWidget.setItem(1, 0, newItem)
        newItem = QTableWidgetItem('女')
        self.tableWidget.setItem(1, 1, newItem)
        newItem = QTableWidgetItem('160')
        self.tableWidget.setItem(1, 2, newItem)

        newItem = QTableWidgetItem('王五')
        self.tableWidget.setItem(2, 0, newItem)
        newItem = QTableWidgetItem('女')
        self.tableWidget.setItem(2, 1, newItem)
        newItem = QTableWidgetItem('170')
        self.tableWidget.setItem(2, 2, newItem)

        self.button =QPushButton('排序')
        self.button.clicked.connect(self.order)
        layout.addWidget(self.button)

        self.orderType =Qt.DescendingOrder
        self.setLayout(layout)


    def order(self):
        if self.orderType ==Qt.DescendingOrder:
            self.orderType =Qt.AscendingOrder
        else:
            self.orderType =Qt.DescendingOrder
        self.tableWidget.sortItems(2,self.orderType)

if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =ColunSort()
    win.show()
    sys.exit(app.exec_())


代码45:
'''
设置单元格的文本对齐方式(左对齐、右对齐)
setTextAlignment
Qt.AlignRight  Qt.AlignBottom
'''

import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtGui import QColor,QBrush,QFont
from PyQt5.QtCore import Qt


class CellTextAlignment(QWidget):
    def __init__(self):
        super(CellTextAlignment,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("设置单元格的文本对齐方式")
        self.resize(430,230);
        layout =QHBoxLayout()
        tableWidget =QTableWidget()
        tableWidget.setRowCount(4)
        tableWidget.setColumnCount(3)
        layout.addWidget(tableWidget)

        tableWidget.setHorizontalHeaderLabels(['姓名','性别','体重(kg)'])

        newItem =QTableWidgetItem('雷神')
        newItem.setTextAlignment(Qt.AlignRight | Qt.AlignBottom)#设置为字体在右侧底端
        tableWidget.setItem(0,0,newItem)

        newItem = QTableWidgetItem('男')
        newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignBottom)  # 设置为字体在右侧底端
        tableWidget.setItem(0, 1, newItem)

        newItem = QTableWidgetItem('190')
        newItem.setTextAlignment(Qt.AlignRight)  # 设置为字体在右侧底端
        tableWidget.setItem(0, 2, newItem)

        self.setLayout(layout)

if __name__ =="__main__":
    app =QApplication(sys.argv)
    win =CellTextAlignment()
    win.show()
    sys.exit(app.exec_())
 

你可能感兴趣的:(python,pytorch,pycharm)