import sys
import os
from PyQt6.QtCore import QUrl
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtWebEngineCore import QWebEngineProfile
from PyQt6.QtWebEngineWidgets import QWebEngineView

class Browser(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建 QWebEngineView 对象
        self.browser = QWebEngineView()

        # 连接 urlChanged 信号到槽方法
        self.browser.urlChanged.connect(self.on_url_changed)

        # 设置初始页面 URL
        self.browser.setUrl(QUrl("https://www.google.com"))

        # 设置窗口为浏览器
        self.setCentralWidget(self.browser)

        # 设置窗口标题和大小
        self.setWindowTitle("PyQt6 Web Browser")
        self.resize(1280, 720)

        # 配置网页的用户代理（可选）
        profile = QWebEngineProfile.defaultProfile()
        profile.setHttpUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36")

    def on_url_changed(self, qurl):
        """
        当 URL 发生变化时调用此方法，打印出新的 URL。
        """
        print(f"当前加载的 URL: {qurl.toString()}")

if __name__ == "__main__":
    # 配置 Chromium 代理设置
    proxy = "socks5://127.0.0.1:7890"  # 替换为实际的代理地址和端口
    # 添加忽略证书错误的标志（仅用于调试）
    chromium_flags = f'--proxy-server={proxy} --ignore-certificate-errors'
    os.environ['QTWEBENGINE_CHROMIUM_FLAGS'] = chromium_flags

    # 启用 WebEngine 日志（可选）
    os.environ['QTWEBENGINE_ENABLE_LOGGING'] = '1'
    os.environ['QTWEBENGINE_DEBUG_BOUND_OBJECTS'] = '1'

    app = QApplication(sys.argv)

    # 创建浏览器窗口
    window = Browser()
    window.show()

    # 进入应用的主循环
    sys.exit(app.exec())     右边帮我添加一个class VideoWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Video Window")
        self.setGeometry(100, 100, 800, 600)
        
        # 使用布局使界面更具可扩展性
        self.layout = QtWidgets.QVBoxLayout()
        self.setLayout(self.layout)
        
        self.label = QtWidgets.QLabel(self)
        self.label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.label.setScaledContents(True)  # 自动缩放图像以适应 QLabel 大小
        self.layout.addWidget(self.label)
        
        # 尝试加载静态图像 '0.jpg' 作为初始画面
        image_path = "9145.png"  # 确保 '0.jpg' 位于当前工作目录或提供完整路径
        test_image = cv2.imread(image_path)
        
        if test_image is not None:
            # 调整图像大小以匹配 QLabel 的尺寸 (800x600)
            test_image = cv2.resize(test_image, (800, 600))
            print(f"Loaded initial image from {image_path}.")
        else:
            # 如果加载失败，使用默认的绿色背景
            print(f"Failed to load {image_path}. Using green screen instead.")
            test_image = np.zeros((600, 800, 3), dtype=np.uint8)
            test_image[:] = (0, 255, 0)  # 绿色背景
        
        self.update_frame(test_image)

    @QtCore.pyqtSlot(np.ndarray)
    def update_frame(self, frame):
        if frame is None:
            print("Received None frame")
            return
        
        if frame.size == 0:
            print("Received empty frame")
            return
        
        try:
            # 确保传入的帧是 BGR 格式，为 OpenCV 默认格式
            if len(frame.shape) == 3 and frame.shape[2] == 3:
                frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            else:
                frame_rgb = frame.copy()
            
            height, width, channel = frame_rgb.shape
            bytes_per_line = 3 * width
            
            # 创建 QImage 对象
            q_image = QtGui.QImage(
                frame_rgb.data,
                width,
                height,
                bytes_per_line,
                QtGui.QImage.Format.Format_RGB888
            )
            
            # 转换为 QPixmap 并设置到 QLabel
            pixmap = QtGui.QPixmap.fromImage(q_image)
            self.label.setPixmap(pixmap)
        except Exception as e:
            print(f"Error updating frame: {e}")
界面需要漂亮