簡體   English   中英

PyQt5 QWebEngineView - 從文件中創建 Markdown - Python

[英]PyQt5 QWebEngineView - Make a Markdown from a file - Python

我有這種方法可以讀取文件並將內容放入純文本中。

def show_open_dialog():
    global file_path
    
    if not save_if_modified():
        return

    file_name, _ = QFileDialog.getOpenFileName(
        window_area, 
        'Open fle...', 
        os.getcwd(), 
        'Text files (*.txt *.py)'
    )

    if file_name:
        with open(file_name, 'r') as f:
            # Print content into text area.
            text_area.setPlainText(f.read())
            
        file_path = file_name

調用此方法時,它會打開一個 window,我可以在其中選擇一個文件並像 Windows 的記事本一樣對其進行充電,並且工作正常。 現在我要做的是使用該文件中的信息創建一個 Markdown,即將其傳遞給 HTML。

我已經創建了 QWebEngineView 元素。

browser_area = QWebEngineView()

這是我在“with open”中所做的修改,但它不起作用。

# Print content into text area.
text_area.setPlainText(f.read())
            
# Raw data.
file_content = f.read()
            
# To HTML.
browser_area.setHtml(file_content)
      
# Show it.
browser_area.show()

打印內容后,只顯示一個空的 window。

我也試過Markdown2 (markdown2.markdown(file_content)) 而不是 .setHtml() 但它也不起作用。

目前我只想在新的 window 中顯示內容,並在無法加載 HTML 時顯示一條消息。

When accessing file objects , the read(size=-1) function reads the size amount of bytes from the stream and puts the stream at that position.

with open('somefile', 'r') as f:
    # reads the first 10 bytes
    start = f.read(10)
    # reads the *next* 10 bytes
    more = f.read(10)
    # move the position at the beginning
    f.seek(0)
    another = f.read(10)
    print(start == another)
    # This will print "True"

如果 size 為 -1(默認),這意味着整個 object 被讀取,然后 position 位於末尾 由於文件末尾沒有任何內容可讀取,因此如果您再次嘗試讀取,顯然您將一無所獲。

如果您需要多次訪問讀取的數據,則應將其存儲在臨時變量中:

with open(file_name, 'r') as f:
    data = f.read()
    text_area.setPlainText(data)
    browser_area.setHtml(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM