PyQt5 공통 컨트롤 및 방법(코드 세그먼트)
34815 단어 자습서
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) #
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 대화 상자에는 아이콘만 다를 뿐 다른 유형은 크게 다르지 않습니다.
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 파일 또는 폴더 열기
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() #
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
반사를 통해 객체 작성반사를 통해 객체를 작성하는 두 가지 방법 1. Class 바이트 객체 newInstance()를 통과합니다.(기본적으로 참조 없음으로 생성됨) 2. 구조기 getConstructor(Class>.parameterT...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.