컴퓨터/Python

PyQt5 다시 시작하기

풍경소리^^ 2022. 5. 10. 15:53

B:\python\vscode

경로주소창에 cmd

python -m venv PyQt5

cd PyQt5

code .

 

Ctrl + `

.\Scripts\activate

pip install pyqt5-tools

B:\python\vscode\PyQt5\Scripts\python.exe -m pip install --upgrade pip

 

Ctrl + Shift + p

python Select Interpreter

venv가 표시된 거 선택

 

https://www.youtube.com/watch?v=oTSene8NFqc&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=2&t=33s 

 

B:\python\vscode\PyQt5\Lib\site-packages\qt5_applications\Qt\bin

designer.exe

 

Widget

생성

 

Line Edit

lineEdit_Entry 이름변경

 

Push Button

button 이름변경

 

저장 B:\python\vscode\app.ui

 

Layouts

Horizontal Layout

 

demo.py--------------------

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5 import uic
class AppDemo(QWidget):
    def __init__(self) -> None:
        super().__init__()
        uic.loadUi('app.ui', self)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = AppDemo()
    demo.show()
    try:
        sys.exit(app.exec_())
    except SystemExit:
        print('Closing Window...')

====================

코드스니펫 활용 - 아직 못함

 

Ctrl + F5 실행

 

demo.py--------------------

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5 import uic
class AppDemo(QWidget):
    def __init__(self) -> None:
        super().__init__()
        uic.loadUi('app.ui', self)
        self.button.clicked.connect(self.printValue)
    def printValue(self):
        print(self.lineEdit_Entry.text())
if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = AppDemo()
    demo.show()
    try:
        sys.exit(app.exec_())
    except SystemExit:
        print('Closing Window...')

====================

 

Ctrl + F5 실행

 

https://www.youtube.com/watch?v=hJEQEECZSH0&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=3 

pip install pandas

example.py--------------------

import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication, QTableView
df = pd.DataFrame({ 'a': ['Mary', 'Jim','John'],
                    'b': [100,200,300],
                    'c': ['a','b','c']})
class pandasModel(QAbstractTableModel):
    def __init__(self) -> None:
        QAbstracTableModel.__init__(self)
        self._data = data
    def rowCount(self, parent=None):
        return self._data.shape[0]
    def columnCount(self, parent=None):
        return self._data.shape[1]
    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
        return None
    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]
        return None
if __name__ == '__main__':
    app = QApplication(sys.argv)
    model = pandasModel(df)
    view = QTableView()
    view.setModel(model)
    view.resize(800,600)
    view.show()
    sys.exit(app.exec_())

====================

example.py--------------------

import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtCore import QAbstractTableModel, Qt
df = pd.DataFrame({ 'a': ['Mary', 'Jim','John'],
                    'b': [100,200,300],
                    'c': ['a','b','c']})
class pandasModel(QAbstractTableModel):
    def __init__(self, data):
        QAbstractTableModel.__init__(self)
        self._data = data
    def rowCount(self, parent=None):
        return self._data.shape[0]
    def columnCount(self, parent=None):
        return self._data.shape[1]
    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
        return None
    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]
        return None
if __name__ == '__main__':
    app = QApplication(sys.argv)
    model = pandasModel(df)
    view = QTableView()
    view.setModel(model)
    view.resize(800,600)
    view.show()
    sys.exit(app.exec_())

====================

https://www.youtube.com/watch?v=ORJI3_DbJyE&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=4 

progressBar.py--------------------

import sys
from PyQt5.QtWidgets import QWidget, QProgressBar, QPushButton, QApplication
from PyQt5.QtCore import QBasicTimer
class ProgressBarDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.progressBar = QProgressBar(self)
        self.progressBar.setGeometry(30,40,200,25)
        self.btnStart = QPushButton('Start', self)
        self.btnStart.move(30,80)
        self.btnStart.clicked.connect(self.startProgress) #TODO
        self.btnReset = QPushButton('Reset', self)
        self.btnReset.move(120, 80)
        self.btnReset.clicked.connect(self.resetBar) #TODO
        self.timer = QBasicTimer()
        self.step = 0
    def resetBar(self):
        self.step = 0
        self.progressBar.setValue(0)
    def startProgress(self):
        if self.timer.isActive():
            self.timer.stop()
            self.btnStart.setText('Start')
        else:
            self.timer.start(100, self)
            self.btnStart.setText('Stop')
    def timerEvent(self, event) -> None:
        if self.step >= 100:
            self.timer.stop()
            self.btnStart.setText('Start')
            return
        self.step +=1
        self.progressBar.setValue(self.step)
if __name__:
    app = QApplication(sys.argv)
    demo = ProgressBarDemo()
    demo.show()
    sys.exit(app.exec_())

====================

https://www.youtube.com/watch?v=Y-8N1dPFsVE&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=6 

https://www.youtube.com/watch?v=tnrYDLMnsgE&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=8 

DragAndDrop.py--------------------

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit
class DragAndDrop(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Drag and Drop')
        self.resize(300, 150)
        self.initUI()
    def initUI(self):
        edit1 = QLineEdit('', self)
        edit1.setDragEnabled(True)
        edit1.move(20, 30)
        edit2 = QLineEdit('', self)
        edit2.setDragEnabled(False)
        edit2.move(20,70) # left, Top
        button = Button('&Button', self)
        button.move(190, 50)
class Button(QPushButton):
    def __init__(self, title, parent):
        super().__init__ (title, parent)
        self.setAcceptDrops(True)
    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat('text/plain'):
            event.accept()
        else:
            event.ignore()
    def dropEvent(self, event):
        print('drop event')
        self.setText(event.mimeData().text())
def main():
    app = QApplication(sys.argv)
    demo = DragAndDrop()
    demo.show()
    sys.exit(app.exec_())
main()

====================

https://www.youtube.com/watch?v=5L6vAu-zBxE&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=9 

icon.py--------------------

from PyQt5.QtWidgets import QApplication, QWidget, QComboBox
from PyQt5.QtGui import QIcon
app = QApplication([])
window = QWidget()
window.resize(300, 150)
combo = QComboBox(window)
combo.resize(100, 50)
combo.move(100, 50)
combo.addItem(QIcon('ok.png'), 'Yes')
combo.addItem(QIcon('no.png'), 'No')
window.show()
app.exec_()

====================

https://www.youtube.com/watch?v=ueCDgo7wc8Y&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=10 

calendarDemo.py--------------------

import sys
from datetime import datetime
import calendar
from PyQt5.QtWidgets import QApplication, QWidget, QCalendarWidget
from PyQt5.QtCore import QDate
class CalendarDemo(QWidget):
    global currentYear, currentMonth
    currentMonth = datetime.now().month
    currentYear = datetime.now().year
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Calendar Demo')
        self.setGeometry(300, 300, 450, 300)
        self.initUI()
    def initUI(self):
        self.calendar = QCalendarWidget(self)
        self.calendar.move(20, 20)
        self.calendar.setGridVisible(True)
        self.calendar.setMinimumDate(QDate(currentYear, currentMonth - 1, 1))
        self.calendar.setMaximumDate(QDate(currentYear, currentMonth + 1, calendar.monthrange(currentYear, currentMonth)[1]))
        self.calendar.setSelectedDate(QDate(currentYear, currentMonth, 1))
        # self.calendar.clicked.connect(lambda dateval:print(dateval.toString()))
        self.calendar.clicked.connect(self.printDateInfo)
    def printDateInfo(self, qDate):
        print('{0}/{1}/{2}'.format(qDate.year(), qDate.month(), qDate.day()))
        print(f'Day Number of the year: {qDate.dayOfYear()}')
        print(f'Day Number of the week: {qDate.dayOfWeek()}')
def main():
    app = QApplication(sys.argv)
    demo = CalendarDemo()
    demo.show()
    sys.exit(app.exec_())
main()

====================

https://www.youtube.com/watch?v=dIa92X2LwDw&list=PL3JVwFmb_BnRpvOeIh_To4YSiebiggyXS&index=11 

a

'컴퓨터 > Python' 카테고리의 다른 글

python qtablewidget excel 실행  (0) 2022.05.17
python mysql  (0) 2022.05.12
pyside6-uic mainwindow.ui -o mainwindow.py  (0) 2022.04.21
python 카카오톡 나에게보내기  (0) 2022.04.20
python win32com excel 단축키 실행  (0) 2022.04.16