오늘은 UI안에 인터넷 창을 띄우는 방법을 적어보려고 한다.
QWebEngineView을 이용할 건데 PyQT5를 설치했더라도 QWebEngineWidgets이 설치가 안돼 있을 것이다.
ModuleNotFoundError: No module named 'PyQt5.QtWebEngineWidgets' 이런 에러가 뜬다면
pip install QWebEngineWidgets 등을 사용해서 설치를 진행하자
예제
아래와 같이 Qt Designer를 사용해서 간단히 UI를 만들어 주었다.
아무래도 인터넷 창이 짤리는 것을 생각해서 QScrollArea를 두고 verticalLayout을 만들어 주었다. 코드를 통해 여기에 webview를 추가해 줄 것이다.
import sys
from PyQt5 import uic
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
main_form = uic.loadUiType(r'web_view.ui')[0]
class web_view(QMainWindow, main_form):
def __init__(self, page="https://rest-time.tistory.com/"):
super().__init__()
self.setupUi(self)
self.webEngineView = QWebEngineView()
self.page = page
self.load_page()
self.verticalLayout_page.addWidget(self.webEngineView)
self.pushButton_refresh.clicked.connect(self.load_page)
def set_page(self, page):
self.page = page
def load_page(self):
try:
print("loading page {}".format(self.page))
if self.page.startswith("http") == False:
self.page = f"http://{self.page}"
self.webEngineView.load(QUrl(self.page))
return True
except:
print("failed to load page")
return False
if __name__ == "__main__":
app = QApplication(sys.argv)
myWindow = web_view()
myWindow.set_page("https://rest-time.tistory.com/")
myWindow.show()
app.exec_()
코드 자체는 심플하다. refresh 버튼을 두어서 클릭하면 페이지를 다시 로드하게 했다.
예제 결과
'Python (파이썬) > PyQT' 카테고리의 다른 글
[PyQT5] Thread 사용하기 (QThread, 간단한 예제) (0) | 2023.04.04 |
---|