PyQt5 공통 컨트롤 및 방법(코드 세그먼트)

34815 단어 자습서
문서 목록
  • PyQt5 프로그램 기본 형식
  • QmainWindow 주 창
  • QLabel 레이블
  • QTextBrowser 텍스트 브라우저
  • QTextEdit 텍스트 편집기
  • QPushButton 키
  • QCheckBox 확인란
  • QRadioButton 라디오 버튼
  • QMessageBox 탄창
  • QSlider 슬라이더
  • QDialog 프롬프트 창
  • QFileDialog 파일 또는 폴더 열기
  • QTreeView 디렉토리 트리 구조
  • QTimer 타이머
  • QSystemTrayIcon 트레이
  • 일반 작업
  • 화면 해상도 확보
  • 화면 캡처 가져오기
  • 콘텐츠 크기에 따라 설정 창 자동 변경
  • 마우스 이벤트 가져오기
  • QPixmap 객체 바이트 스트리밍
  • PyQt5 프로그램 기본 형식
    import sys
    from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel
    from ui import Ui_MainWindow #  qtdesigner      
    
    class MyApp(QMainWindow, Ui_MainWindow):
        def __init__(self):
            super(MyApp, self).__init__()
            self.setupUi(self)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = MyApp()
        window.show()
        sys.exit(app.exec_())
    

    QmainWindow 주 창
    기본 창 속성 설정, 가운데 표시
    import sys
    from PyQt5.QtGui import QIcon
    from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication
    
    
    class MyApp(QMainWindow):
        def __init__(self):
            super(MyApp, self).__init__()
            self.resize(512, 512)  #        
            self.status = self.statusBar()  #         
            self.status.showMessage('     ', 4000)  # #             showMessage(‘    ’,    (    ))
            self.setWindowTitle('     ')  #       
            self.setWindowIcon(QIcon('logo.png'))  #     
            self.move_center()
    
    
        def move_center(self):
            screen = QDesktopWidget().screenGeometry()
            form = self.geometry()
            x_move_step = (screen.width() - form.width()) / 2
            y_move_step = (screen.height() - form.height()) / 2
            self.move(x_move_step, y_move_step)
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = MyApp()
        window.show()
        sys.exit(app.exec_())
    

    QLabel 태그
  • 읽기 텍스트 표시
  • label = QLabel(self)
    label.setText("    ")  #   
    text = label.text()  #   
    
  • 디스플레이 이미지
  • label = QLabel(self)
    pixmap = QPixmap("    ")
    label.setPixmap(pixmap)
    label.setScaledContents(True) #      QLabel    
    label.setAlignment(Qt.AlignCenter)  #         
    
  • opencv 디스플레이 이미지와 결합
  • label = QLabel(self)
    label.setPixmap(QPixmap("")) #   QLabel    
    img = cv2.imread("    ") #     ,       
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # bgr -> rgb
    h, w, c = img.shape #       
    image = QImage(img, w, h, 3 * w, QImage.Format_RGB888)
    pixmap = QPixmap.fromImage(image)
    label.setPixmap(pixmap)
    label.setScaledContents(True) #      QLabel    
    

    QTextBrowser 텍스트 브라우저
    설정, 추가, 텍스트 가져오기
    text_browser = QTextBrowser(self)
    text_browser.setText(a) #     
    text_browser.append(a) #     
    text = text_browser.toPlainText() #     
    

    QTextEdit 텍스트 편집기
    설정, 추가, 텍스트 가져오기
    text_edit = QTextEdit(self)
    text_edit.setText(a) #     
    text_edit.append(a) #     
    text = text_edit.toPlainText() #     
    

    QPushButton 키
    이벤트 트리거 누르기
    button = QPushButton(self)
    button .setChecked() #       
    button.clicked.connect(clicked_function) #     
    
    def clicked_function():
    	pass
    

    QCheckBox 확인란
    check_box = QCheckBox(self)
    check_box.setChecked() #        
    check_box.setCheckable(True) #        
    check_box.stateChanged.connect(check_box_changed) #       check_box_changed  
    
    def use_external_camera(self, status):
        if status == Qt.Checked: #       
    		pass 
        else:
    		pass
    

    QRadioButton 라디오 버튼
    radio_button1 = QRadioButton()
    radio_button2 = QRadioButton()
    
    radio_button1.setChecked(True) #     ,         
    radio_button1.toggled.connect(radio_button_changed) #     radio_button_changed  
    radio_button2.setChecked(False) #      
    radio_button2.toggled.connect(radio_button_changed) #     radio_button_changed  (       )
    
    def radio_button_changed():
        if radio_button1.isChecked(): #      
            pass
        elif radio_button2.isChecked():
            pass
    

    QMessageBox 팝업 상자
    QMessageBox 대화 상자에는 아이콘만 다를 뿐 다른 유형은 크게 다르지 않습니다.
  • QMessageBox.정보 상자
  • QMessageBox.question Q&A 상자
  • QMessageBox.warning 경고
  • QMessageBox.ctitical 위험
  • QMessageBox.about 정보
  • reply = QMessageBox.information(self, "  ", "  ", QMessageBox.Yes | QMessageBox.No)
    if reply==QMessageBox.Yes:
        ...
    else:
        ...
    
    

    QSlider 슬라이더 막대
    슬라이더 막대 상하한 설정, 현재 값 설정, 슬라이딩 트리거 이벤트
    slider = QSlider()
    slider.setOrientation(Qtcore.Qt.Horizontal) #         
    # slider.setOrientation(Qtcore.Qt.Vertical) #         
    slider.setMaximum(100) #      
    slider.setMinimum(0) #      
    slider.setValue(72) #      
    value = slider.value() #     
    slider.valueChanged.connect(change_function) #       change_function  
    

    QDialog 프롬프트 창
    dialog = QDialog()
    dialog.adjustSize() #          
    text = QLineEdit(message, dialog) #           
    text.adjustSize()
    #         ApplicationModal  ,         ,       
    dialog.setWindowModality(Qt.ApplicationModal)
    dialog.exec_() #     ,   show       
    

    QFileDialog 파일 또는 폴더 열기
  • QFileDialog.getOpenFileName 파일 이름 가져오기
  • QFileDialog.getExistingDirectory 폴더 이름 가져오기
  • file_name, _ = QFileDialog.getOpenFileName(self, '  ', './', 'Image files(*.jpg *.gif *.png)') #               
    folder_name = QFileDialog.getExistingDirectory(self, '  ', './') #        
    

    QTreeView 디렉토리 트리 구조
    디렉터리 트리 결과를 만들고 현재 경로의 트리 구조를 표시하며 파일 트리거 함수를 두 번 클릭합니다
    tree_model = QDirModel() 
    #   
    # tree_model = QFileSystemModel()
    # tree_model.setRootPath(os.getcwd()) #           
    tree_view = QTreeView()
    tree_view.setModel(tree_model )
    tree_view.setRootIndex(self.dirModel.index(os.getcwd())) #       (         C   )
    tree_view.setWindowTitle(self.treeView.tr("    ")) #   title...     
    treeView.doubleClicked.connect(tree_cilcked_function) #       tree_cilcked_function  
    tree_view.show()
    
    #       
    def tree_cilcked_function(self, file_index):
    	file_name = tree_model.filePath(file_index)
    	...
    

    QTimer 타이머
    타이머 시간, 트리거 시간, 순환 실행 설정
    timer = QTimer()
    timer.timeout.connect(process_function)
    timer.start(20) #        20ms,      
    timer.stop() #      
    def process_function():
    	···
    

    QSystemTrayIcon 트레이
    tray = QSystemTrayIcon(QIcon('./icon/cut.png'), self)  #         ,     
    tray.activated.connect(func)  #             
    tray_menu = QMenu(QApplication.desktop())  #     
    action1 = QAction(u'   ', self, triggered=func2)  #           (     )
    action2 = QAction(u'   ', self, triggered=fun3)  #           (    )
    tray_menu.addAction(action1)  #        
    tray_menu.addAction(action2)
    tray.setContextMenu(tray_menu)  #         
    tray.show()
    

    일반 작업
    화면 해상도 가져오기
    desktop = QApplication.desktop()
    #           
    screenRect = desktop.screenGeometry()
    height = self.screenRect.height()
    width = self.screenRect.width()
    

    화면 캡처 가져오기
    screen = QApplication.primaryScreen()
    pixmap = screen.grabWindow(0)
    

    설정 창은 내용 크기에 따라 자동으로 변경됩니다
    QWidget().adjustSize()
    

    마우스 이벤트 가져오기
        def mousePressEvent(self, QMouseEvent):
    		pass
    
        def mouseReleaseEvent(self, QMouseEvent):
    		pass
    
        def mouseMoveEvent(self, QMouseEvent):
    		pass
    

    QmouseEvent의 일반 속성
    QMouseEvent.x()				#     x
    QMouseEvent.y()				#     y
    QMouseEvent.button()		#   ,     Qt.LeftButton / Qt.RightButton
    

    QPixmap 객체 바이트 스트리밍
    shot_bytes = QByteArray()
    buffer = QBuffer(shot_bytes)
    buffer.open(QIODevice.WriteOnly)
    shot_img = self.get_shot_img()
    shot_img.save(buffer, 'png')			#    buffer  
    data = shot_bytes.data()				#      
    

    좋은 웹페이지 즐겨찾기