Обновление виджетов PyQt6 QLabel в реальном времени + обрезка текстаPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Обновление виджетов PyQt6 QLabel в реальном времени + обрезка текста

Сообщение Anonymous »

Я работаю над приложением Swiftly, используя PyQt6. Две проблемы заключаются в том, что я не могу заставить обнаружение батареи psutil работать в РЕАЛЬНОМ ВРЕМЕНИ, будучи интегрированным в графический интерфейс, и что по какой-то причине большинство виджетов QLabel в «дом» обрезается справа. Что касается средства проверки заряда батареи, я просмотрел некоторые форумы и онлайн-руководства по PyQt6, но не смог заставить его работать с моим собственным приложением, поскольку оно содержит более 200 строк и не так просто (в нем много методов и ООП). Что касается проблемы отсечения, единственное решение, которое я нашел, — это добавление примерно 20 пробелов в конце каждой QLabel, что я нашел не только утомительной и плохой практикой, но вы просто не делаете этого из-за недостаточной эффективности в случае, например 50 виджетов QLabel. Не обращайте внимания на неиспользованный импорт, он предназначен для использования в будущем. Вот текущий код:

Код: Выделить всё

# Imports
import sqlite3 as swiftlySQL_Database
import hashlib as hashDecrypt_SHA256_
import psutil as systemConfigurations
from time import sleep as waitSeconds
import os as configureOperatingSystem
from PyQt6.QtCore import Qt, QMargins
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QLineEdit, QPushButton
from PyQt6.QtGui import QChildWindowEvent, QColorConstants, QClipboard, QCursor, QImage, QFont

# Password and file health checking (later add)
def checkHash(fileDirectoryPath, expectedHash):
with open(fileDirectoryPath, 'rb') as file:
hashFunc = hashDecrypt_SHA256_.sha256()
for chunk in iter(lambda: file.read(256), b''): hashFunc.update(chunk)
return True if hashFunc.hexdigest() == expectedHash else False
print(checkHash('shtough.txt', 'c7134d40055420b2010edacb28cf7eee030801934b43992b493a6e854d6bf3af'))

def reportUserStatistics():
directoryUser = (name := systemConfigurations.users()[0].name) if systemConfigurations.users() else None # Multiple?
operationDirectoryPath = input('\nApplication "Swiftly" requests a directory path to perform its operations: ') # Replace with formatted QLineEdit
if not operationDirectoryPath: operationDirectoryPath = f'/Users/{directoryUser}'; print('"Swiftly": received an empty input. Proceeding with terminal user. ')
diskStorageStatistics = systemConfigurations.disk_usage(operationDirectoryPath); sentRecvStatistics = systemConfigurations.net_io_counters()
diskStorageUsed = f'{round(diskStorageStatistics.used / 1_000_000_000, 2)} GB'; diskStorageTotal = f'{round(diskStorageStatistics.total / 1_000_000_000, 2)} GB'
userSentTotal = f'{round(sentRecvStatistics.bytes_sent / 1_000_000_000, 2)} GB, {sentRecvStatistics.errin} errors. '
userRecvTotal = f'{round(sentRecvStatistics.bytes_recv / 1_000_000_000, 2)} GB, {sentRecvStatistics.errout} errors.  '

def ScanNetworkFrequency(tick = 1):
before = systemConfigurations.net_io_counters()
waitSeconds(tick) # Crucial
after = systemConfigurations.net_io_counters()
bytesSentDuringTick = after.bytes_sent - before.bytes_sent; bytesRecvDuringTick = after.bytes_recv - before.bytes_recv
networkFrequencySent = f'{round(bytesSentDuringTick / tick / 1_000, 1)} KB/s'; networkFrequencyRecv = f'{round(bytesRecvDuringTick / tick / 1_000, 2)} KB/s'
return (networkFrequencySent, networkFrequencyRecv)

# Application Blueprint
class swiftlyApp(QMainWindow):
def mousePressEvent(self, event): self.usernameInput.clearFocus(); self.passwordInput.clearFocus()
def __init__(self):
super().__init__()
self.setWindowTitle('Swiftly')
self.setWindowFlags(Qt.WindowType.FramelessWindowHint); self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.resize(QApplication.primaryScreen().availableSize().width(), QApplication.primaryScreen().availableSize().height())
self.appBackground = QWidget() # Serving as background and an artificial container
self.appBackground.setStyleSheet('background: #339deb; border-radius: 25px; ')
self.setCentralWidget(self.appBackground)
self.authenticationWidgets = []  # For future widget deletion/removal
authenticationTitle = QLabel('Sign Into Swiftly', self.appBackground)
authenticationTitle.setFont(QFont('', 40, 700)); authenticationTitle.move(120, 120)
authenticationTitle.setStyleSheet('color: white; background: transparent; ')
self.authenticationWidgets.append(authenticationTitle)
usernameLabel = QLabel('Username', self.appBackground)
usernameLabel.setFont(QFont('', 20, 400)); usernameLabel.move(120, 240)
usernameLabel.setStyleSheet('color: white; background: transparent; letter-spacing: 1px; ')
self.authenticationWidgets.append(usernameLabel)
self.usernameInput = QLineEdit(self.appBackground)
self.usernameInput.setFont(QFont('', 20, 400))
self.usernameInput.setStyleSheet('background-color: transparent; '
'border: none; border-bottom: 2px solid white; '
'color: white; letter-spacing: 1px; '
'padding-left: -1px; ')
self.usernameInput.resize(300, 30); self.usernameInput.move(120, 270)
self.authenticationWidgets.append(self.usernameInput)
passwordLabel = QLabel('Password', self.appBackground)
passwordLabel.setFont(QFont('', 20, 400)); passwordLabel.move(120, 360)
passwordLabel.setStyleSheet('color: white; background: transparent; letter-spacing: 1px; ')
self.authenticationWidgets.append(passwordLabel)
self.passwordInput = QLineEdit(self.appBackground)
self.passwordInput.setFont(QFont('', 20, 400))
self.passwordInput.setEchoMode(QLineEdit.EchoMode.Password)
self.passwordInput.setStyleSheet('background-color: transparent; '
'border: none; border-bottom: 2px solid white; '
'color: white; letter-spacing: 1px; '
'padding-left: -2px; ')
self.passwordInput.resize(300, 30); self.passwordInput.move(120, 390)
self.authenticationWidgets.append(self.passwordInput)
button = QPushButton('Authenticate', self.appBackground)
button.setFont(QFont('', 20, 400))
button.resize(300, 55); button.move(120, 480)
button.setStyleSheet('background-color: #0c5a9c; '
'border: none; '
'border-radius: 5px; '
'color: white; letter-spacing: 1px; ')
button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.authenticationWidgets.append(button)
self.usernameInput.returnPressed.connect(lambda: self.passwordInput.setFocus())
self.passwordInput.returnPressed.connect(self.appInitiate)
button.clicked.connect(self.appInitiate)

def appInitiate(self):
username = self.usernameInput.text();  password = self.passwordInput.text()
if username == 'hi' and password == 'hi':
for widget in self.authenticationWidgets: widget.hide()
self.appSidebar = QWidget(parent = self.appBackground) # Serving as sidebar background and widget container
self.appSidebar.setFixedSize(288, QApplication.primaryScreen().availableSize().height())
self.appSidebar.setStyleSheet('background-color: #0c5a9c; '
'border-top-left-radius: 25px; '
'border-top-right-radius: 0px; '
'border-bottom-left-radius: 25px; '
'border-bottom-right-radius: 0px; '); self.appSidebar.show()
self.mainContentWidgets = []  # For future widget deletion/removal
appTitle = QLabel('Swiftly', self.appBackground)
appTitle.setFont(QFont('', 40, 700))
appTitle.move(60, 120); appTitle.show()
appTitle.setStyleSheet('background: transparent; color: white; ')
appHome = QPushButton('Home', self.appBackground)
appHome.clicked.connect(self.homeInitiate)
appHome.setFont(QFont('', 20, 400))
appHome.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
appHome.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
appHome.move(60, 240); appHome.show()
appReports = QPushButton('Reports', self.appBackground)
appReports.clicked.connect(self.reportsInitiate)
appReports.setFont(QFont('', 20, 400))
appReports.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
appReports.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
appReports.move(60, 300); appReports.show()
appDevice = QPushButton('Device Issues', self.appBackground)
appDevice.clicked.connect(self.deviceInitiate)
appDevice.setFont(QFont('', 20, 400))
appDevice.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
appDevice.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
appDevice.move(60, 360); appDevice.show()
appPay = QPushButton('Payment', self.appBackground)
appPay.clicked.connect(self.payInitiate)
appPay.setFont(QFont('', 20, 400))
appPay.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
appPay.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
appPay.move(60, 420); appPay.show()
appSettings = QPushButton('Settings', self.appBackground)
appSettings.clicked.connect(self.settingsInitiate)
appSettings.setFont(QFont('', 20, 400))
appSettings.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
appSettings.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
appSettings.move(60, 480); appSettings.show()
appLogout = QPushButton('Sign Out', self.appBackground)
appLogout.clicked.connect(self.logoutInitiate)
appLogout.setFont(QFont('', 20, 400))
appLogout.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
appLogout.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
appLogout.move(60, 540); appLogout.show()
self.homeInitiate() # Configuring home as default

def homeInitiate(self):
for widget in self.mainContentWidgets: widget.hide()
homeTitle = QLabel('Welcome back to Swiftly. ', self.appBackground)
homeTitle.setFont(QFont('', 40, 700)); homeTitle.show()
homeTitle.setStyleSheet('background: transparent; color: white; ')
homeTitle.move(408, 120); self.mainContentWidgets.append(homeTitle)
homeSubtitle = QLabel("It's good to have you back! Check out our newest update in the feed. ", self.appBackground)
homeSubtitle.setFont(QFont('', 20, 400)); homeSubtitle.show()
homeSubtitle.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
homeSubtitle.move(408, 240); self.mainContentWidgets.append(homeSubtitle)
updateFeedTitle = QLabel('Update v1.3.18 Release.      ', self.appBackground)
updateFeedTitle.setFont(QFont('', 20, 400)); updateFeedTitle.show()
updateFeedTitle.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
updateFeedTitle.move(408, 300); self.mainContentWidgets.append(updateFeedTitle)
updateFeedText = QLabel('We are attempting to reduce the amount of battery used for Swiftly. ', self.appBackground)
updateFeedText.setFont(QFont('', 20, 400)); updateFeedText.show()
updateFeedText.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
updateFeedText.move(408, 360); self.mainContentWidgets.append(updateFeedText)
isCharging = systemConfigurations.sensors_battery()
if isCharging.power_plugged: batteryInfoText = QLabel(f'We know that your battery is charging, {isCharging.percent}%. ', self.appBackground)
else: batteryInfoText = QLabel(f'We know that your battery is not charging, {isCharging.percent}%. ', self.appBackground)
batteryInfoText.setFont(QFont('', 20, 400)); batteryInfoText.show()
batteryInfoText.setStyleSheet('background: transparent; color: white; letter-spacing: 1px; ')
batteryInfoText.move(408, 420); self.mainContentWidgets.append(batteryInfoText)

def reportsInitiate(self):
for widget in self.mainContentWidgets: widget.hide()
reportsTitle = QLabel('Reports. ', self.appBackground)
reportsTitle.setFont(QFont('', 40, 700)); reportsTitle.show()
reportsTitle.setStyleSheet('background: transparent; color: white; ')
reportsTitle.move(408, 120); self.mainContentWidgets.append(reportsTitle)

def deviceInitiate(self):
for widget in self.mainContentWidgets: widget.hide()
deviceTitle = QLabel('Issues we found. ', self.appBackground)
deviceTitle.setFont(QFont('', 40, 700)); deviceTitle.show()
deviceTitle.setStyleSheet('background: transparent; color: white; ')
deviceTitle.move(408, 120); self.mainContentWidgets.append(deviceTitle)

def payInitiate(self):
for widget in self.mainContentWidgets: widget.hide()
payTitle = QLabel('Upgrade Or Cancel. ', self.appBackground)
payTitle.setFont(QFont('', 40, 700)); payTitle.show()
payTitle.setStyleSheet('background: transparent; color: white; ')
payTitle.move(408, 120); self.mainContentWidgets.append(payTitle)

def settingsInitiate(self):
for widget in self.mainContentWidgets: widget.hide()
settingsTitle = QLabel('Customize how we manage your device. ', self.appBackground)
settingsTitle.setFont(QFont('', 40, 700)); settingsTitle.show()
settingsTitle.setStyleSheet('background: transparent; color: white; ')
settingsTitle.move(408, 120); self.mainContentWidgets.append(settingsTitle)

def logoutInitiate(self):
for widget in self.mainContentWidgets: widget.hide()
logoutTitle = QLabel('Are you sure? ', self.appBackground)
logoutTitle.setFont(QFont('', 40, 700)); logoutTitle.show()
logoutTitle.setStyleSheet('background: transparent; color: white; ')
logoutTitle.move(408, 120); self.mainContentWidgets.append(logoutTitle)

# Statistics
import platform as operatingSystem # Checking user platform
if operatingSystem.system() != 'Darwin':
print(f'\n"Swiftly" is an application available for MacOS devices only. You are currently running on {operatingSystem.system()}. ')
print(f'{configureOperatingSystem.environ.get('SHELL')}: gave consent to perform action "Force Quit" on application "Swiftly". \n')
configureOperatingSystem.abort() # Attempt zero message abort

# Requiring Authentication
if __name__ == '__main__':
erm = QApplication([])
app = swiftlyApp()
app.show()  # Kill Wait
erm.exec()  # Execution
Может ли кто-нибудь помочь мне решить проблему с отображением заряда батареи в реальном времени, интегрированным в сложное приложение, а также с случайным вырезанием текста для виджетов QLabel в «домашнем меню»?

Подробнее здесь: https://stackoverflow.com/questions/791 ... t-clipping
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Обновление виджетов PyQt6 QLabel в реальном времени + обрезка текста
    Anonymous » » в форуме Python
    0 Ответы
    29 Просмотры
    Последнее сообщение Anonymous
  • Обновление меток PyQt6 в реальном времени + обрезка текста
    Anonymous » » в форуме Python
    0 Ответы
    7 Просмотры
    Последнее сообщение Anonymous
  • Обновление меток PyQt6 в реальном времени + обрезка текста
    Anonymous » » в форуме Python
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Переместите QLabel с помощью QPropertyAnimation на основе Qpoint в QGridLayout в PyQT6.
    Anonymous » » в форуме Python
    0 Ответы
    34 Просмотры
    Последнее сообщение Anonymous
  • Как изменить параметры конфигурации набора виджетов iOS на основе семейства виджетов
    Anonymous » » в форуме IOS
    0 Ответы
    29 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»