杰瑞科技汇

Python中如何使用QLCDNumber?

Of course! In Python, you don't have a direct equivalent to Qt's QLCDNumber widget, but you can achieve the exact same look and feel using the standard QLCDNumber from the PyQt or PySide libraries.

Python中如何使用QLCDNumber?-图1
(图片来源网络,侵删)

Here's a complete guide on how to use QLCDNumber in Python, covering the basics, common use cases, and customization.

The Basic Concept

QLCDNumber is a widget designed to display numbers. It has a "look and feel" similar to the LCD displays on electronic devices like calculators, microwaves, or digital clocks. It's perfect for displaying numerical data in a visually distinct way.

You will need to install one of the Qt bindings for Python if you haven't already.

Installation:

Python中如何使用QLCDNumber?-图2
(图片来源网络,侵删)
# For PyQt5
pip install PyQt5
# For PySide6 (the recommended choice for new projects)
pip install PySide6

Simple Example: Displaying a Number

Let's start with the most basic example: creating a window and displaying a number.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLCDNumber, QVBoxLayout, QWidget
# --- For PySide6, use these imports instead ---
# from PySide6.QtWidgets import QApplication, QMainWindow, QLCDNumber, QVBoxLayout, QWidget
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QLCDNumber Basic Example")
        self.setGeometry(100, 100, 300, 150)
        # Create the central widget and layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        # 1. Create the QLCDNumber widget
        # You can specify the number of digits it should have
        self.lcd = QLCDNumber(8) # 8-digit display
        # 2. Set the initial value
        self.lcd.display(12345678)
        # 3. Add the widget to the layout
        layout.addWidget(self.lcd)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Explanation:

  1. QLCDNumber(8): We create an instance of QLCDNumber. By passing 8, we tell it to be sized for an 8-digit number. If you don't provide a number, it defaults to 5.
  2. self.lcd.display(12345678): This is the most important method. It takes an integer, a float, or a string and displays it on the LCD.
  3. layout.addWidget(self.lcd): We add the widget to our window's layout so it becomes visible.

Common Use Case: Creating a Simple Counter

A very common use for QLCDNumber is as a display for a counter. This demonstrates how to update the value dynamically.

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLCDNumber, 
                             QPushButton, QVBoxLayout, QWidget)
from PyQt5.QtCore import QTimer
# --- For PySide6, use these imports instead ---
# from PySide6.QtWidgets import (QApplication, QMainWindow, QLCDNumber, 
#                              QPushButton, QVBoxLayout, QWidget)
# from PySide6.QtCore import QTimer
class CounterWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QLCDNumber Counter")
        self.setGeometry(200, 200, 300, 200)
        # --- Setup UI ---
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        self.lcd = QLCDNumber(5)
        self.lcd.display(0)
        self.button_increment = QPushButton("Increment")
        self.button_reset = QPushButton("Reset")
        layout.addWidget(self.lcd)
        layout.addWidget(self.button_increment)
        layout.addWidget(self.button_reset)
        # --- Connect Signals and Slots ---
        self.button_increment.clicked.connect(self.increment_counter)
        self.button_reset.clicked.connect(self.reset_counter)
        # --- Timer for automatic increment ---
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.increment_counter)
        # self.timer.start(1000) # Uncomment to auto-increment every second
    def increment_counter(self):
        current_value = self.lcd.value() # Get current value
        self.lcd.display(current_value + 1)
    def reset_counter(self):
        self.lcd.display(0)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = CounterWindow()
    window.show()
    sys.exit(app.exec_())

Key additions:

Python中如何使用QLCDNumber?-图3
(图片来源网络,侵删)
  • self.lcd.value(): This method retrieves the current integer value from the display.
  • QPushButton: We add buttons to interact with the counter.
  • clicked.connect(): We connect the button's clicked signal to our custom functions (slots).
  • QTimer: I've included an example of using a QTimer to automatically increment the counter, which is very powerful for creating clocks or gauges.

Customizing the Appearance

QLCDNumber offers several ways to change its look.

A. Mode: Integer vs. Hex vs. Octal vs. Bin

You can change the number system used for display.

self.lcd = QLCDNumber()
self.lcd.display(255)
# Set the display mode
self.lcd.setMode(QLCDNumber.Hex)   # Displays FF
# self.lcd.setMode(QLCDNumber.Dec) # Default, displays 255
# self.lcd.setMode(QLCDNumber.Oct) # Displays 377
# self.lcd.setMode(QLCDNumber.Bin) # Displays 11111111

B. Segment Style

You can change the style of the segments that make up the numbers.

# Segment styles
# QLCDNumber.Outline (default)
# QLCDNumber.Filled
# QLCDNumber.Flat
self.lcd.setSegmentStyle(QLCDNumber.Filled)

Here's a visual representation of the styles:

  • Outline: Standard hollow segments.
  • Filled: Solid segments.
  • Flat: Filled segments with a beveled, 3D-like edge.

C. Customizing the Look and Feel with Stylesheets

For more advanced customization, you can use Qt's Stylesheets, similar to CSS for web pages.

# Example of using a stylesheet
self.lcd.setStyleSheet("""
   QLCDNumber {
        background-color: #2b2b2b;
        color: #00ff41; /* LCD Green */
        border: 2px solid #555;
        border-radius: 5px;
    }
""")

This will give your LCD a dark background with a classic green glow.


Complete Example: A Digital Clock

This example combines QLCDNumber with QTimer to create a simple digital clock.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLCDNumber, QVBoxLayout, QWidget
from PyQt5.QtCore import QTimer, QTime
# --- For PySide6, use these imports instead ---
# from PySide6.QtWidgets import QApplication, QMainWindow, QLCDNumber, QVBoxLayout, QWidget
# from PySide6.QtCore import QTimer, QTime
class ClockWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Digital Clock")
        self.setGeometry(300, 300, 350, 150)
        # --- Setup UI ---
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        self.lcd = QLCDNumber(8) # HH:MM:SS format
        self.lcd.setSegmentStyle(QLCDNumber.Filled)
        self.lcd.setStyleSheet("QLCDNumber { color: cyan; }")
        layout.addWidget(self.lcd)
        # --- Setup Timer ---
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_time)
        self.timer.start(1000) # Update every 1000 ms (1 second)
        # Initial update
        self.update_time()
    def update_time(self):
        # Get the current time
        current_time = QTime.currentTime()
        # Format the time as a string (e.g., "12:34:56")
        time_text = current_time.toString("hh:mm:ss")
        # Display the formatted time string
        self.lcd.display(time_text)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ClockWindow()
    window.show()
    sys.exit(app.exec_())

Summary of Key QLCDNumber Methods

Method Description
display(num) Displays an integer, float, or string. The primary method for setting the value.
value() Returns the current integer value.
setDigitCount(n) Sets the number of digits the widget can hold. Resizes the widget accordingly.
setMode(mode) Sets the number system (Hex, Dec, Oct, Bin).
setSegmentStyle(style) Sets the visual style of the segments (Outline, Filled, Flat).
setSmallDecimalPoint(b) If True, shows a smaller decimal point.
checkRange(value) Checks if a value is within the display's range and returns a clamped value.
分享:
扫描分享到社交APP
上一篇
下一篇