去除 python qt QWebEngineView 菜单
Jump to turn (7)
- User
去除 python qt QWebEngineView 菜单
- Assistant
你可以使用以下代码隐藏菜单:
python
去除 python qt QWebEngineView 菜单
你可以使用以下代码隐藏菜单:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QAction
from PyQt5.QtWebEngineWidgets import QWebEngineView
class MyWebEngineView(QWebEngineView):
def createWindow(self, _type):
new_webview = MyWebEngineView(self)
return new_webview
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setCentralWidget(MyWebEngineView(self))
self.menuBar().clear() # Remove all menus
self.webview = self.findChild(QWebEngineView) # Get the QWebEngineView instance
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
这样将隐藏所有菜单,包括右键菜单。如果你只想隐藏右键菜单,可以尝试以下代码:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QAction
from PyQt5.QtWebEngineWidgets import QWebEngineView
class MyWebEngineView(QWebEngineView):
def createWindow(self, _type):
new_webview = MyWebEngineView(self)
return new_webview
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setCentralWidget(MyWebEngineView(self))
self.webview = self.findChild(QWebEngineView) # Get the QWebEngineView instance
# Remove the right-click context menu
self.webview.setContextMenuPolicy(Qt.NoContextMenu)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
这段代码将只隐藏右键菜单。
QWebEngineView printToPdf 生成完成后提示
你可以通过重写QWebEnginePage的pdfPrintingFinished信号来实现在生成PDF完成后给出提示。例如:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenuBar, QAction, QMessageBox
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PyQt5.QtPrintSupport import QPrinter
class MyWebEnginePage(QWebEnginePage):
def pdfPrintingFinished(self, filePath, success):
if success:
QMessageBox.information(self.view(), "PDF Saved", f"PDF saved to {filePath}")
else:
QMessageBox.critical(self.view(), "PDF Error", "Could not save PDF")
class MyWebEngineView(QWebEngineView):
def __init__(self, parent=None):
super().__init__(parent)
self.setPage(MyWebEnginePage(self))
def printToPdf(self):
options = QPrinter()
options.setOutputFormat(QPrinter.PdfFormat)
options.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter)
options.setFullPage(True)
options.setResolution(300)
# Define save path
filePath, _ = QFileDialog.getSaveFileName(self, "Save PDF", "", "PDF Files (*.pdf)")
if filePath:
self.page().pdfPrintingFinished.connect(lambda filePath=filePath: self.page().pdfPrintingFinished(filePath, True))
self.page().printToPdf(options)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setCentralWidget(MyWebEngineView(self))
self.webview = self.findChild(QWebEngineView) # Get the QWebEngineView instance
# Add Print to PDF action
self.printToPdfAction = QAction("Print to PDF", self)
self.printToPdfAction.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_P))
self.printToPdfAction.triggered.connect(self.webview.printToPdf)
# Add File menu and Print to PDF action
fileMenu = self.menuBar().addMenu("File")
fileMenu.addAction(self.printToPdfAction)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
在这个示例中,将QWebEnginePage子类化为MyWebEnginePage并重写pdfPrintingFinished信号。在这个信号槽内,我们检查PDF是否生成成功,并使用QMessageBox弹出提醒窗口。在MyWebEngineView中,我们定义printToPdf方法来启动PDF生成,重写pdfPrintingFinished信号并在PDF生成完成后显示窗口提示信息。
http://127.0.0.1:8000/markdown_idnex.html?file=test.md&xxxpp=111 用 js 正则将其 分为 [file,test.md,xxxpp,111 ]
你可以使用正则表达式来提取链接中的参数信息。以下是一个Python示例代码:
import re
url = "http://127.0.0.1:8000/markdown_idnex.html?file=test.md&xxxpp=111"
# Define the regex pattern to match the URL parameters
pattern = r'\?(.*)$'
# Find the parameters using the regex pattern
matches = re.findall(pattern, url)
# Get the first match which will contain the parameters
if matches:
parameters = matches[0].split('&')
for parameter in parameters:
# Split each parameter into its key and value
key, value = parameter.split('=')
print(key, value)
这个代码将打印出链接中的参数信息,以key-value对的形式输出:
file test.md
xxxpp 111
你可以使用类似的方法在JavaScript中提取链接参数。例如:
var url = 'http://127.0.0.1:8000/markdown_idnex.html?file=test.md&xxxpp=111';
var pattern = /\?(.*)$/;
var matches = url.match(pattern);
if (matches) {
var parameters = matches[1].split('&');
for (var i = 0; i < parameters.length; i++) {
var parts = parameters[i].split('=');
var key = parts[0];
var value = parts[1];
console.log(key, value);
}
}
这个代码将在控制台中打印出链接中的参数信息。
python QWebEngineView 与 页面 js 通讯
你可以在Python中使用QWebChannel来实现QWebEngineView和页面JavaScript之间的通信。以下是一个简单的示例:
import sys
from PyQt5.QtCore import pyqtSignal, QObject, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel, QWebChannelAbstractTransport
# Create a Bridge class to connect Python and JavaScript
class Bridge(QObject):
info_printed = pyqtSignal(str) # Define a PyQt signal to emit a message to JavaScript
# Create a method to be called by JavaScript
def print_info(self, info):
print(info)
self.info_printed.emit(info) # Emit the PyQt signal to JavaScript
class WebChannelTransport(QWebChannelAbstractTransport):
def __init__(self, parent=None):
super().__init__(parent)
self.messages = []
def sendMessage(self, message, _id):
self.messages.append(message)
def flush(self):
for message in self.messages:
self.emitMessage(message)
self.messages.clear()
class MainWindow(QWebEngineView):
def __init__(self, parent=None):
super().__init__(parent)
bridge = Bridge(self)
bridge.info_printed.connect(lambda value: print(f"JavaScript emitted {value}"))
channel = QWebChannel()
channel.registerObject("bridge", bridge)
transport = WebChannelTransport(self)
channel.registerTransport(transport)
self.page().setWebChannel(channel)
self.load(QUrl.fromLocalFile('test.html'))
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
在这个示例中,我们创建了一个名为Bridge的类,使用pyqtSignal定义了一个信号info_printed,用于从Python向JavaScript发送消息。该类还创建了一个方法print_info,以便在JavaScript调用时打印一条消息并触发信号。
在MainWindow类中,我们创建了一个Bridge实例和一个QWebChannel实例,将其注册到页面上。我们还自定义了WebChannelTransport类来处理消息传递。在页面JavaScript中,你可以使用以下代码从Python中调用print_info方法并将消息发送回Python:
var bridge = new QWebChannel(qt.webChannelTransport, function (channel) {
var pythonBridge = channel.objects.bridge;
pythonBridge.print_info("Hello, Python!");
});
该代码使用QWebChannel对象连接Python和JavaScript,并通过channel.objects对象获取名为bridge的Python对象。然后它调用print_info方法并将消息发送回Python。当Python的Bridge对象调用info_printed信号时,可以收到这个消息。
python qt 到时触发
你可以使用QTimer来实现Python Qt中的定时器,并在特定时间触发操作。以下是一个简单的示例:
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QLabel
class MainWindow(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.timer = QTimer(self) # Create a QTimer instance
# Connect the QTimer timeout signal to a method
self.timer.timeout.connect(self.handle_timeout)
# Set the interval and start the timer
self.timer.start(1000) # Timer will fire every second
def handle_timeout(self):
print("Timer fired!")
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
在这个示例中,我们创建了一个名为MainWindow的类,继承自QLabel,然后在类的构造函数中创建了一个QTimer实例。我们将QTimer的timeout信号连接到一个名为handle_timeout的方法,该方法将在特定时间间隔内执行。我们使用start方法启动定时器。
您可以根据需要调整timeout信号出现的间隔时间。在handle_timeout方法中,您可以实现在时间到达时期望的行为。在这个示例中,我们只是打印了一条消息。
触发一次
如果你希望定时器只触发一次,可以在定时器启动后使用QTimer.singleShot()方法来定义只触发一次的延迟执行任务。以下是一个示例:
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QLabel
class MainWindow(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.timer = QTimer(self)
self.timer.timeout.connect(self.handle_timeout)
# Set the interval and start the timer
self.timer.start(1000)
# Define a singleShot timer to stop the original timer after 5 seconds
QTimer.singleShot(5000, self.timer.stop)
def handle_timeout(self):
print("Timer fired!")
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
在这个示例中,我们定义了一个名为handle_timeout的方法,用于执行定时器超时时期望的操作。我们还在构造函数中定义了一个额外的QTimer.singleShot()定时器,用于停止原始定时器,在5秒后只执行一次。
注意,QTimer.singleShot()方法的第一个参数是延迟毫秒数,第二个参数是将在超时时调用的函数。在这个示例中,我们将timer.stop作为函数传递给singleShot方法,以确保只触发一次并停止原始定时器。
pdfkit 等页面加载完 打印
你可以使用Python的pdfkit库将HTML网页转换为PDF格式,然后使用QPrinter在隐藏的应用程序窗口中打印PDF文件。以下是一个简单的示例:
import sys
import os
import pdfkit
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence, QPrinter
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction
from PyQt5.QtWebEngineWidgets import QWebEngineView
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
# Create a QWebEngineView instance
self.webview = QWebEngineView(self)
self.setCentralWidget(self.webview)
# Load a web page
self.load_url('https://stackoverflow.com')
# Create an action to trigger printing
self.printAction = QAction("Print", self)
self.printAction.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_P))
self.printAction.triggered.connect(self.printPdf)
# Add the print action to the File menu
file_menu = self.menuBar().addMenu("File")
file_menu.addAction(self.printAction)
def load_url(self, url):
self.webview.load(url)
self.webview.loadFinished.connect(self.on_load_finished)
def on_load_finished(self, ok):
if ok:
# Convert the web page to a pdf
pdfkit.from_url(self.webview.url().toString(), 'output.pdf')
def printPdf(self):
printer = QPrinter(QPrinter.HighResolution)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter)
printer.setFullPage(True)
printer.setResolution(300)
# Load the pdf into the webview for printing
self.webview.load('file://' + os.path.abspath('output.pdf'))
# Show the print dialog
self.webview.print(printer)
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
在这个示例中,我们创建了一个名为MainWindow的类,其中包含一个QWebEngineView实例。我们加载一个网页,并通过pdfkit将其转换为PDF并保存在名为output.pdf的文件中。然后,我们创建一个触发打印操作的printAction,并将其添加到菜单栏的“文件”菜单中。在printPdf方法中,我们创建一个QPrinter实例,使用load()方法将PDF加载到QWebEngineView中,然后使用print()方法触发打印操作。