A Self-hosted Archiving Service integrated with Internet Archive

Wayback

Wayback is a tool that supports running as a command-line tool and docker container, purpose to snapshot webpage to time capsules.

Features

  • Free and open-source
  • Cross-platform compatibility
  • Batch wayback URLs for faster archiving
  • Built-in CLI (wayback) for convenient use
  • Serve as a Tor Hidden Service or local web entry for added privacy and accessibility
  • Easier wayback to Internet Archive, archive.today, IPFS and Telegraph integration
  • Interactive with IRC, Matrix, Telegram bot, Discord bot, Mastodon, and Twitter as a daemon service for convenient use
  • Supports publishing wayback results to Telegram channel, Mastodon, and GitHub Issues for sharing
  • Supports storing archived files to disk for offline use
  • Download streaming media (requires FFmpeg) for convenient media archiving.

Installation

The simplest, cross-platform way is to download from GitHub Releases and place the executable file in your PATH.

From source:

go install github.com/wabarc/wayback/cmd/wayback@latest

From GitHub Releases:

curl -fsSL https://github.com/wabarc/wayback/raw/main/install.sh | sh

or via Bina:

curl -fsSL https://bina.egoist.dev/wabarc/wayback | sh

Using Snapcraft (on GNU/Linux)

sudo snap install wayback

Via APT:

curl -fsSL https://repo.wabarc.eu.org/apt/gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/packages.wabarc.gpg
echo "deb [arch=amd64,arm64,armhf signed-by=/usr/share/keyrings/packages.wabarc.gpg] https://repo.wabarc.eu.org/apt/ /" | sudo tee /etc/apt/sources.list.d/wayback.list
sudo apt update
sudo apt install wayback

Via RPM:

sudo rpm --import https://repo.wabarc.eu.org/yum/gpg.key
sudo tee /etc/yum.repos.d/wayback.repo > /dev/null <<EOT
[wayback]
name=Wayback Archiver
baseurl=https://repo.wabarc.eu.org/yum/
enabled=1
gpgcheck=1
gpgkey=https://repo.wabarc.eu.org/yum/gpg.key
EOT

sudo dnf install -y wayback

Via Homebrew:

brew tap wabarc/wayback
brew install wayback

Usage

Command line

$ wayback -h

A command-line tool and daemon service for archiving webpages.

Usage:
  wayback [flags]

Examples:
  wayback https://www.wikipedia.org
  wayback https://www.fsf.org https://www.eff.org
  wayback --ia https://www.fsf.org
  wayback --ia --is -d telegram -t your-telegram-bot-token
  WAYBACK_SLOT=pinata WAYBACK_APIKEY=YOUR-PINATA-APIKEY \
    WAYBACK_SECRET=YOUR-PINATA-SECRET wayback --ip https://www.fsf.org

Flags:
      --chatid string      Telegram channel id
  -c, --config string      Configuration file path, defaults: ./wayback.conf, ~/wayback.conf, /etc/wayback.conf
  -d, --daemon strings     Run as daemon service, supported services are telegram, web, mastodon, twitter, discord, slack, irc
      --debug              Enable debug mode (default mode is false)
  -h, --help               help for wayback
      --ia                 Wayback webpages to Internet Archive
      --info               Show application information
      --ip                 Wayback webpages to IPFS
      --ipfs-host string   IPFS daemon host, do not require, unless enable ipfs (default "127.0.0.1")
  -m, --ipfs-mode string   IPFS mode (default "pinner")
  -p, --ipfs-port uint     IPFS daemon port (default 5001)
      --is                 Wayback webpages to Archive Today
      --ph                 Wayback webpages to Telegraph
      --print              Show application configurations
  -t, --token string       Telegram Bot API Token
      --tor                Snapshot webpage via Tor anonymity network
      --tor-key string     The private key for Tor Hidden Service
  -v, --version            version for wayback

Examples

Wayback one or more url to Internet Archive and archive.today:

wayback https://www.wikipedia.org

wayback https://www.fsf.org https://www.eff.org

Wayback url to Internet Archive or archive.today or IPFS:

// Internet Archive
$ wayback --ia https://www.fsf.org

// archive.today
$ wayback --is https://www.fsf.org

// IPFS
$ wayback --ip https://www.fsf.org

For using IPFS, also can specify a pinning service:

$ export WAYBACK_SLOT=pinata
$ export WAYBACK_APIKEY=YOUR-PINATA-APIKEY
$ export WAYBACK_SECRET=YOUR-PINATA-SECRET
$ wayback --ip https://www.fsf.org

// or

$ WAYBACK_SLOT=pinata WAYBACK_APIKEY=YOUR-PINATA-APIKEY \
$ WAYBACK_SECRET=YOUR-PINATA-SECRET wayback --ip https://www.fsf.org

More details about pinning service.

With telegram bot:

wayback --ia --is --ip -d telegram -t your-telegram-bot-token

Publish message to your Telegram channel at the same time:

wayback --ia --is --ip -d telegram -t your-telegram-bot-token --chatid your-telegram-channel-name

Also can run with debug mode:

wayback -d telegram -t YOUR-BOT-TOKEN --debug

Both serve on Telegram and Tor hidden service:

wayback -d telegram -t YOUT-BOT-TOKEN -d web

URLs from file:

wayback url.txt
cat url.txt | wayback

Configuration Parameters

By default, wayback looks for configuration options from this files, the following are parsed:

  • ./wayback.conf
  • ~/wayback.conf
  • /etc/wayback.conf

Use the -c / --config option to specify the build definition file to use.

You can also specify configuration options either via command flags or via environment variables, an overview of all options below.

FlagsEnvironment VariableDefaultDescription
--debugDEBUGfalseEnable debug mode, override LOG_LEVEL
-c, --config--Configuration file path, defaults: ./wayback.conf, ~/wayback.conf, /etc/wayback.conf
-LOG_TIMEtrueDisplay the date and time in log messages
-LOG_LEVELinfoLog level, supported level are debug, info, warn, error, fatal, defaults to info
-ENABLE_METRICSfalseEnable metrics collector
-WAYBACK_LISTEN_ADDR0.0.0.0:8964The listen address for the HTTP server
-CHROME_REMOTE_ADDR-Chrome/Chromium remote debugging address, for screenshot, format: host:port, wss://domain.tld
-WAYBACK_POOLING_SIZE3Number of worker pool for wayback at once
-WAYBACK_BOLT_PATH./wayback.dbFile path of bolt database
-WAYBACK_STORAGE_DIR-Directory to store binary file, e.g. PDF, html file
-WAYBACK_MAX_MEDIA_SIZE512MBMax size to limit download stream media
-WAYBACK_MEDIA_SITES-Extra media websites wish to be supported, separate with comma
-WAYBACK_TIMEOUT300Timeout for single wayback request, defaults to 300 second
-WAYBACK_MAX_RETRIES2Max retries for single wayback request, defaults to 2
-WAYBACK_USERAGENTWaybackArchiver/1.0User-Agent for a wayback request
-WAYBACK_FALLBACKoffUse Google cache as a fallback if the original webpage is unavailable
-WAYBACK_MEILI_ENDPOINT-Meilisearch API endpoint
-WAYBACK_MEILI_INDEXINGcapsulesMeilisearch indexing name
-WAYBACK_MEILI_APIKEY-Meilisearch admin API key
-d, --daemon--Run as daemon service, e.g. telegram, web, mastodon, twitter, discord
--iaWAYBACK_ENABLE_IAtrueWayback webpages to Internet Archive
--isWAYBACK_ENABLE_IStrueWayback webpages to Archive Today
--ipWAYBACK_ENABLE_IPfalseWayback webpages to IPFS
--phWAYBACK_ENABLE_PHfalseWayback webpages to Telegra.ph, required Chrome/Chromium
--ipfs-hostWAYBACK_IPFS_HOST127.0.0.1IPFS daemon service host
-p, --ipfs-portWAYBACK_IPFS_PORT5001IPFS daemon service port
-m, --ipfs-modeWAYBACK_IPFS_MODEpinnerIPFS mode for preserve webpage, e.g. daemon, pinner
-WAYBACK_IPFS_TARGETweb3storageThe IPFS pinning service is used to store files, supported pinners: infura, pinata, nftstorage, web3storage.
-WAYBACK_IPFS_APIKEY-Apikey of the IPFS pinning service
-WAYBACK_IPFS_SECRET-Secret of the IPFS pinning service
-WAYBACK_GITHUB_TOKEN-GitHub Personal Access Token, required the repo scope
-WAYBACK_GITHUB_OWNER-GitHub account name
-WAYBACK_GITHUB_REPO-GitHub repository to publish results
-WAYBACK_NOTION_TOKEN-Notion integration token
-WAYBACK_NOTION_DATABASE_ID-Notion database ID for archiving results
-t, --tokenWAYBACK_TELEGRAM_TOKEN-Telegram Bot API Token
--chatidWAYBACK_TELEGRAM_CHANNEL-The Telegram public/private channel id to publish archive result
-WAYBACK_TELEGRAM_HELPTEXT-The help text for Telegram command
-WAYBACK_MASTODON_SERVER-Domain of Mastodon instance
-WAYBACK_MASTODON_KEY-The client key of your Mastodon application
-WAYBACK_MASTODON_SECRET-The client secret of your Mastodon application
-WAYBACK_MASTODON_TOKEN-The access token of your Mastodon application
-WAYBACK_TWITTER_CONSUMER_KEY-The customer key of your Twitter application
-WAYBACK_TWITTER_CONSUMER_SECRET-The customer secret of your Twitter application
-WAYBACK_TWITTER_ACCESS_TOKEN-The access token of your Twitter application
-WAYBACK_TWITTER_ACCESS_SECRET-The access secret of your Twitter application
-WAYBACK_IRC_NICK-IRC nick
-WAYBACK_IRC_PASSWORD-IRC password
-WAYBACK_IRC_CHANNEL-IRC channel
-WAYBACK_IRC_SERVERirc.libera.chat:6697IRC server, required TLS
-WAYBACK_MATRIX_HOMESERVERhttps://matrix.orgMatrix homeserver
-WAYBACK_MATRIX_USERID-Matrix unique user ID, format: @foo:example.com
-WAYBACK_MATRIX_ROOMID-Matrix internal room ID, format: !bar:example.com
-WAYBACK_MATRIX_PASSWORD-Matrix password
-WAYBACK_DISCORD_BOT_TOKEN-Discord bot authorization token
-WAYBACK_DISCORD_CHANNEL-Discord channel ID, find channel ID
-WAYBACK_DISCORD_HELPTEXT-The help text for Discord command
-WAYBACK_SLACK_APP_TOKEN-App-Level Token of Slack app
-WAYBACK_SLACK_BOT_TOKEN-Bot User OAuth Token for Slack workspace, use User OAuth Token if requires create external link
-WAYBACK_SLACK_CHANNEL-Channel ID of Slack channel
-WAYBACK_SLACK_HELPTEXT-The help text for Slack slash command
-WAYBACK_NOSTR_RELAY_URLwss://nostr.developer.liNostr relay server url, multiple separated by comma
-WAYBACK_NOSTR_PRIVATE_KEY-The private key of a Nostr account
--torWAYBACK_USE_TORfalseSnapshot webpage via Tor anonymity network
--tor-keyWAYBACK_TOR_PRIVKEY-The private key for Tor Hidden Service
-WAYBACK_TOR_LOCAL_PORT8964Local port for Tor Hidden Service, also support for a reverse proxy. This is ignored if WAYBACK_LISTEN_ADDR is set.
-WAYBACK_TOR_REMOTE_PORTS80Remote ports for Tor Hidden Service, e.g. WAYBACK_TOR_REMOTE_PORTS=80,81
-WAYBACK_SLOT-Pinning service for IPFS mode of pinner, see ipfs-pinner
-WAYBACK_APIKEY-API key for pinning service
-WAYBACK_SECRET-API secret for pinning service

If both of the definition file and environment variables are specified, they are all will be read and apply, and preferred from the environment variable for the same item.

Prints the resulting options of the targets with --print, in a Go struct with type, without running the wayback.

Docker/Podman

docker pull wabarc/wayback
docker run -d wabarc/wayback wayback -d telegram -t YOUR-BOT-TOKEN # without telegram channel
docker run -d wabarc/wayback wayback -d telegram -t YOUR-BOT-TOKEN -c YOUR-CHANNEL-USERNAME # with telegram channel

1-Click Deploy

Deploy Deploy to Render

Deployment

Documentation

For a comprehensive guide, please refer to the complete documentation.

Contributing

We encourage all contributions to this repository! Open an issue! Or open a Pull Request!

If you're interested in contributing to wayback itself, read our contributing guide to get started.

Note: All interaction here should conform to the Code of Conduct.


Supported Golang version: See .github/workflows/testing.yml


Download Details:

Author: Wabarc
Source Code: https://github.com/wabarc/wayback 
License: GPL-3.0 license

#heroku #screenshot #twitter #telegram #matrix #go #golang 

What is GEEK

Buddha Community

A Self-hosted Archiving Service integrated with Internet Archive
Wasswa  Meagan

Wasswa Meagan

1679657598

Create QProgressbar with QThread Real Example | PyQt5 | Python

In this python - PyQt5 tutorial we will learn about How to create a QProgressbar using QThread Real Example | PyQt5 | Python. A progress bar is used to give the user an indication of the progress of an operation and to reassure them that the application is still running.

What is PyQt5 QProgressbar ?

QProgressBar widget consists of horizontal or vertical bar that fills up gradually to indicate the progress of a task. it is often used in applications that involve time consuming operations, such as file uploads or downloads, software installations or any other process that may take a while to complete.

QProgressBar widget can be customized to display different colors, fonts, and sizes. It also provides various properties and methods that allow developers to control its behavior, such as the minimum and maximum values, the current value, and the orientation of the bar.

Overall, the QProgressBar widget is a useful tool for providing visual feedback to users on the progress of a task and can help make applications more user-friendly and intuitive.

These are the imports that we need for example


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time

This is our thread class and this class extends from QThread, a QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.


class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)

After we create our Window class that extends from QDialog and in that class we add the requirements of our window like title, geometry and icon with QProgresBar and also a QPushButton. also we have used some style and design for our progressbar.

class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::chunk {background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()

These are the methods that we are going to use for starting and setting the value of the QProgressBar.


  def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)

Also every PyQt5 application must create an application object. 

App = QApplication(sys.argv)

Finally, we enter the mainloop of the application. The event handling starts from this point. 

window = Window()
sys.exit(App.exec_())

Complete source code for QProgressbar with QThread


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time
 
 
class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)
class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::
        # chunk {background:
        # qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()
 
    def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)
 
 
 
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

This will be the result of the code for the PyQt5 QProgressBar.

PyQt5 QProgressbar With QThread Practical Example

PyQt5 QProgressbar With QThread Practical Example

Also you can watch the complete video for PyQt5 QProgressbar With QThread Practical Example.

article source at: https://codeloop.org

#python #pyqt5 

создать QProgressbar с реальным примером QThread | PyQt5 | Python

В этом руководстве по python — PyQt5 мы узнаем, как создать QProgressbar с использованием реального примера QThread | PyQt5 | Python. Индикатор выполнения используется для индикации пользователем хода выполнения операции и подтверждения того, что приложение все еще работает.

Что такое PyQt5 QProgressbar?

Виджет QProgressBar состоит из горизонтальной или вертикальной полосы, которая постепенно заполняется, показывая ход выполнения задачи. он часто используется в приложениях, которые включают в себя трудоемкие операции, такие как загрузка или загрузка файлов, установка программного обеспечения или любой другой процесс, который может занять некоторое время.

Виджет QProgressBar можно настроить для отображения различных цветов, шрифтов и размеров. Он также предоставляет различные свойства и методы, которые позволяют разработчикам управлять его поведением, например минимальное и максимальное значения, текущее значение и ориентацию полосы.

В целом, виджет QProgressBar является полезным инструментом для обеспечения визуальной обратной связи с пользователями о ходе выполнения задачи и может помочь сделать приложения более удобными и интуитивно понятными.

Это импорт, который нам нужен, например


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time

Это наш класс потока, и этот класс расширяется от QThread, объект QThread управляет одним потоком управления внутри программы. QThreads начинают выполняться в run(). По умолчанию run() запускает цикл событий, вызывая exec(), и запускает цикл событий Qt внутри потока.


class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)

После того, как мы создадим наш класс Window, который расширяется от QDialog, и в этот класс мы добавим требования к нашему окну, такие как заголовок, геометрия и значок с помощью QProgresBar, а также QPushButton . также мы использовали некоторый стиль и дизайн для нашего индикатора выполнения.

class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::chunk {background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()

Это методы, которые мы собираемся использовать для запуска и установки значения QProgressBar.


  def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)

Также каждое приложение PyQt5 должно создавать объект приложения. 

App = QApplication(sys.argv)

Наконец, мы входим в основной цикл приложения. Обработка события начинается с этой точки. 

window = Window()
sys.exit(App.exec_())

Полный исходный код для QProgressbar с QThread


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time
 
 
class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)
class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::
        # chunk {background:
        # qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()
 
    def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)
 
 
 
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

Это будет результат кода для PyQt5 QProgressBar.

PyQt5 QProgressbar с практическим примером QThread

PyQt5 QProgressbar с практическим примером QThread

Также вы можете посмотреть полное видео для PyQt5 QProgressbar с практическим примером QThread.

источник статьи: https://codeloop.org

#python  #pyqt5 

Criar QProgressbar com QThread Exemplo Real | PyQt5 | Python

Neste tutorial python - PyQt5 aprenderemos como criar uma QProgressbar usando QThread Real Example | PyQt5 | Python. Uma barra de progresso é usada para dar ao usuário uma indicação do progresso de uma operação e para assegurar que o aplicativo ainda está em execução.

O que é PyQt5 QProgressbar?

O widget QProgressBar consiste em uma barra horizontal ou vertical que é preenchida gradualmente para indicar o andamento de uma tarefa. é frequentemente usado em aplicativos que envolvem operações demoradas, como uploads ou downloads de arquivos, instalações de software ou qualquer outro processo que pode demorar um pouco para ser concluído.

O widget QProgressBar pode ser personalizado para exibir diferentes cores, fontes e tamanhos. Ele também fornece várias propriedades e métodos que permitem aos desenvolvedores controlar seu comportamento, como os valores mínimo e máximo, o valor atual e a orientação da barra.

No geral, o widget QProgressBar é uma ferramenta útil para fornecer feedback visual aos usuários sobre o andamento de uma tarefa e pode ajudar a tornar os aplicativos mais fáceis de usar e intuitivos.

Estas são as importações que precisamos, por exemplo


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time

Esta é nossa classe de encadeamento e esta classe se estende de QThread, um objeto QThread gerencia um encadeamento de controle dentro do programa. QThreads começam a executar em run(). Por padrão, run() inicia o loop de evento chamando exec() e executa um loop de evento Qt dentro do thread.


class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)

Depois criamos nossa classe Window que estende de QDialog e nessa classe adicionamos os requisitos de nossa janela como título, geometria e ícone com QProgresBar e também um QPushButton. também usamos algum estilo e design para nossa barra de progresso.

class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::chunk {background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()

Esses são os métodos que usaremos para iniciar e definir o valor de QProgressBar.


  def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)

Além disso, todo aplicativo PyQt5 deve criar um objeto de aplicativo. 

App = QApplication(sys.argv)

Por fim, entramos no mainloop da aplicação. A manipulação do evento começa a partir deste ponto. 

window = Window()
sys.exit(App.exec_())

Código-fonte completo para QProgressbar com QThread


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time
 
 
class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)
class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::
        # chunk {background:
        # qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()
 
    def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)
 
 
 
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

Este será o resultado do código para o PyQt5 QProgressBar.

PyQt5 QProgressbar com QThread Exemplo prático

PyQt5 QProgressbar com QThread Exemplo prático

Além disso, você pode assistir ao vídeo completo do exemplo prático PyQt5 QProgressbar com QThread.

fonte do artigo em: https://codeloop.org

#python  #pyqt5 

鈕 筑

鈕 筑

1679966160

用QThread 实例创建QProgressbar | PyQt5 | Python

在这个 python - PyQt5 教程中,我们将学习如何使用 QThread Real Example 创建 QProgressbar | PyQt5 | Python。进度条用于向用户指示操作的进度,并向他们保证应用程序仍在运行。

什么是 PyQt5 QProgressbar?

QProgressBar小部件由逐渐填充的水平或垂直条组成,以指示任务的进度。它通常用于涉及耗时操作的应用程序,例如文件上传或下载、软件安装或任何其他可能需要一段时间才能完成的过程。

QProgressBar 小部件可以被定制以显示不同的颜色、字体和大小。它还提供了各种属性和方法,允许开发人员控制其行为,例如最小值和最大值、当前值以及条形图的方向。

总的来说,QProgressBar 小部件是一个有用的工具,可以向用户提供有关任务进度的视觉反馈,并且可以帮助使应用程序更加用户友好和直观。

例如,这些是我们需要的导入


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time

这是我们的线程类,这个类从QThread 扩展而来,一个 QThread 对象在程序中管理一个线程控制。QThreads 在 run() 中开始执行。默认情况下,run() 通过调用 exec() 启动事件循环,并在线程内运行 Qt 事件循环。


class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)

在我们创建了从 QDialog 扩展的 Window 类之后,我们在该类中添加了我们的窗口的要求,如标题、几何图形和带有 QProgresBar 的图标以及 QPushButton 我们还为我们的进度条使用了一些风格和设计。

class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::chunk {background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()

这些是我们将用于启动和设置 QProgressBar 值的方法。


  def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)

此外,每个 PyQt5 应用程序都必须创建一个应用程序对象。 

App = QApplication(sys.argv)

最后,我们进入应用程序的主循环。事件处理从这一点开始。 

window = Window()
sys.exit(App.exec_())

带有 QThread 的 QProgressbar 的完整源代码


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time
 
 
class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)
class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::
        # chunk {background:
        # qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()
 
    def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)
 
 
 
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

这将是 PyQt5 QProgressBar 代码的结果。

PyQt5 QProgressbar With QThread 实例

PyQt5 QProgressbar With QThread 实例

您也可以观看 PyQt5 QProgressbar With QThread Practical Example 的完整视频。

文章来源:https: //codeloop.org

#python #pyqt5 

Duy  Tien

Duy Tien

1679720773

Tạo QProgressbar với QThread Ví dụ thực tế | PyQt5 | Python

Trong hướng dẫn python - PyQt5 này, chúng ta sẽ tìm hiểu về Cách tạo QProgressbar bằng QThread Ví dụ thực tế | PyQt5 | con trăn. Thanh tiến trình được sử dụng để cung cấp cho người dùng chỉ báo về tiến trình của một thao tác và để đảm bảo với họ rằng ứng dụng vẫn đang chạy.

PyQt5 QProgressbar là gì?

Tiện ích QProgressBar bao gồm thanh ngang hoặc dọc lấp đầy dần dần để cho biết tiến trình của một tác vụ. nó thường được sử dụng trong các ứng dụng liên quan đến các thao tác tốn thời gian, chẳng hạn như tải lên hoặc tải xuống tệp, cài đặt phần mềm hoặc bất kỳ quy trình nào khác có thể mất một lúc để hoàn thành.

Tiện ích QProgressBar có thể được tùy chỉnh để hiển thị các màu, phông chữ và kích cỡ khác nhau. Nó cũng cung cấp các thuộc tính và phương thức khác nhau cho phép các nhà phát triển kiểm soát hành vi của nó, chẳng hạn như giá trị tối thiểu và tối đa, giá trị hiện tại và hướng của thanh.

Nhìn chung, tiện ích QProgressBar là một công cụ hữu ích để cung cấp phản hồi trực quan cho người dùng về tiến độ của một tác vụ và có thể giúp làm cho ứng dụng trở nên thân thiện và trực quan hơn với người dùng.

Đây là những hàng nhập khẩu mà chúng ta cần chẳng hạn


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time

Đây là lớp luồng của chúng tôi và lớp này mở rộng từ QThread, một đối tượng QThread quản lý một luồng điều khiển trong chương trình. QThreads bắt đầu thực thi trong run(). Theo mặc định, run() bắt đầu vòng lặp sự kiện bằng cách gọi hàm exec() và chạy vòng lặp sự kiện Qt bên trong luồng.


class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)

Sau khi chúng tôi tạo lớp Cửa sổ mở rộng từ QDialog và trong lớp đó, chúng tôi thêm các yêu cầu của cửa sổ như tiêu đề, hình học và biểu tượng bằng QProgresBar và cả QPushButton . chúng tôi cũng đã sử dụng một số phong cách và thiết kế cho thanh tiến trình của mình.

class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::chunk {background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()

Đây là những phương pháp mà chúng ta sẽ sử dụng để bắt đầu và thiết lập giá trị của QProgressBar.


  def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)

Ngoài ra, mọi ứng dụng PyQt5 phải tạo một đối tượng ứng dụng. 

App = QApplication(sys.argv)

Cuối cùng, chúng tôi vào vòng lặp chính của ứng dụng. Việc xử lý sự kiện bắt đầu từ thời điểm này. 

window = Window()
sys.exit(App.exec_())

Hoàn thành mã nguồn cho QProgressbar với QThread


from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import time
 
 
class MyThread(QThread):
    # Create a counter thread
    change_value = pyqtSignal(int)
    def run(self):
        cnt = 0
        while cnt < 100:
            cnt+=1
            time.sleep(0.3)
            self.change_value.emit(cnt)
class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 ProgressBar"
        self.top = 200
        self.left = 500
        self.width = 300
        self.height = 100
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.progressbar = QProgressBar()
        #self.progressbar.setOrientation(Qt.Vertical)
        self.progressbar.setMaximum(100)
        self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
                                       "QProgressBar::chunk {background:yellow}")
        #qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white);
        #self.progressbar.setStyleSheet("QProgressBar::
        # chunk {background:
        # qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 red, stop: 1 white); }")
        #self.progressbar.setTextVisible(False)
        vbox.addWidget(self.progressbar)
        self.button = QPushButton("Start Progressbar")
        self.button.clicked.connect(self.startProgressBar)
        self.button.setStyleSheet('background-color:yellow')
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.show()
 
    def startProgressBar(self):
        self.thread = MyThread()
        self.thread.change_value.connect(self.setProgressVal)
        self.thread.start()
 
    def setProgressVal(self, val):
        self.progressbar.setValue(val)
 
 
 
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

Đây sẽ là kết quả của mã cho PyQt5 QProgressBar.

PyQt5 QProgressbar với QThread Ví dụ thực tế

PyQt5 QProgressbar với QThread Ví dụ thực tế

Ngoài ra, bạn có thể xem video hoàn chỉnh cho PyQt5 QProgressbar Với Ví dụ thực tế về QThread.

nguồn bài viết tại: https://codeloop.org

#python  #pyqt5