Add scrollwheel support and arrow key support from switch back and forth between images here is code import pickle
import tempfile
import time
from enum import IntEnum
from types import SimpleNamespace as sn
import cv2
import numpy as np
import numpy.linalg as npla
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from core import imagelib, pathex
from core.cv2ex import *
from core.imagelib import SegIEPolys, SegIEPolyType, sd
from core.qtex import *
from DFLIMG import *
from samplelib import PackedFaceset
from .QCursorDB import QCursorDB
from .QIconDB import QIconDB
from .QStringDB import QStringDB
from .QImageDB import QImageDB
To add scroll wheel support and arrow key navigation for switching between images in your PyQt5 application, you'll need to override the event handlers in the main image display widget. Below, I'll guide you through the steps to implement this functionality, integrating it with your existing code structure.
Assumptions
Main Image Display Widget: I assume you have a main widget (e.g., ImageViewer) responsible for displaying the current image.
Image List and Indexing: There's a list of images and an index to keep track of the currently displayed image.
Integration with ImagePreviewSequenceBar: The preview bar should update accordingly when the main image changes.
If your architecture differs, you might need to adjust the integration points accordingly.
Step 1: Implement the Main Image Display Widget
First, create or modify your main image display widget to handle key and wheel events. Here's an example of how you can implement this:
python
class ImageViewer(QWidget):
def __init__(self, image_list, preview_bar, parent=None):
super().__init__(parent)
self.image_list = image_list # List of image file paths or numpy arrays
self.current_index = 0
self.preview_bar = preview_bar # Instance of ImagePreviewSequenceBar
# Setup QLabel to display the image
self.image_label = QLabel()
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
# Layout
layout = QVBoxLayout()
layout.addWidget(self.image_label)
self.setLayout(layout)
# Display the first image
self.display_image()
# Ensure the widget can receive focus to handle key events
self.setFocusPolicy(Qt.StrongFocus)
def display_image(self):
"""
Display the image at the current index.
"""
if 0 <= self.current_index < len(self.image_list):
image = self.image_list[self.current_index]
# If image is a file path, load it using QPixmap
if isinstance(image, str):
pixmap = QPixmap(image)
elif isinstance(image, np.ndarray):
# Convert numpy array to QImage
height, width, channel = image.shape
bytes_per_line = 3 * width
q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
pixmap = QPixmap.fromImage(q_image)
else:
raise TypeError("Unsupported image type")
self.image_label.setPixmap(pixmap.scaled(
self.image_label.size(),
Qt.KeepAspectRatio,
Qt.SmoothTransformation
))
# Update the preview bar
self.update_preview_bar()
def resizeEvent(self, event):
"""
Ensure the image scales with the window.
"""
self.display_image()
super().resizeEvent(event)
def keyPressEvent(self, event):
"""
Handle left and right arrow keys to navigate images.
"""
if event.key() == Qt.Key_Right:
self.next_image()
elif event.key() == Qt.Key_Left:
self.previous_image()
else:
super().keyPressEvent(event)
def wheelEvent(self, event):
"""
Handle mouse wheel events to navigate images.
"""
delta = event.angleDelta().y()
if delta > 0:
self.previous_image()
elif delta < 0:
self.next_image()
def next_image(self):
"""
Navigate to the next image.
"""
if self.current_index < len(self.image_list) - 1:
self.current_index += 1
self.display_image()
else:
QMessageBox.information(self, "End of Images", "You have reached the last image.")
def previous_image(self):
"""
Navigate to the previous image.
"""
if self.current_index > 0:
self.current_index -= 1
self.display_image()
else:
QMessageBox.information(self, "Start of Images", "You are at the first image.")
def update_preview_bar(self):
"""
Update the preview bar with surrounding images.
"""
# Define the number of previous and next images to show
count = self.preview_bar.get_preview_images_count() // 2
# Get previous images
prev_imgs = []
for i in range(1, count + 1):
idx = self.current_index - i
if idx >= 0:
prev_imgs.append(self.image_list[idx])
else:
prev_imgs.append(None) # Placeholder for no image
# Get next images
next_imgs = []
for i in range(1, count + 1):
idx = self.current_index + i
if idx < len(self.image_list):
next_imgs.append(self.image_list[idx])
else:
next_imgs.append(None) # Placeholder for no image
self.preview_bar.update_images(prev_imgs=prev_imgs, next_imgs=next_imgs)
Step 2: Integrate with ImagePreviewSequenceBar
Assuming you have an instance of ImagePreviewSequenceBar, you'll need to initialize ImageViewer with it. Here's how you can set up your main window:
python
class MainWindow(QMainWindow):
def __init__(self, image_list, parent=None):
super().__init__(parent)
self.setWindowTitle("Image Viewer with Navigation")
# Configuration
QUIConfig.initialize(icon_size=48, icon_spacer_size=16, preview_bar_icon_size=64)
# Initialize the preview bar
preview_images_count = 4 # Number of preview images on each side
self.preview_bar = ImagePreviewSequenceBar(preview_images_count=preview_images_count, icon_size=QUIConfig.preview_bar_icon_q_size.width())
# Initialize the main image viewer
self.image_viewer = ImageViewer(image_list=image_list, preview_bar=self.preview_bar)
# Layout
central_widget = QWidget()
main_layout = QVBoxLayout()
main_layout.addWidget(self.image_viewer)
main_layout.addWidget(self.preview_bar)
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
# Optionally, add controls from QCanvasControlsLeftBar
self.controls_left_bar = QCanvasControlsLeftBar()
main_layout.addWidget(self.controls_left_bar)
# Connect control signals if necessary
# Example: self.controls_left_bar.btn_next.clicked.connect(self.image_viewer.next_image)
Step 3: Ensure Focus for Key Events
For the ImageViewer to receive key events, it needs to have focus. You can set it to focus automatically when the application starts:
If you want the preview bar to reflect the currently selected image more prominently, you can modify the update_images method to highlight the current image or adjust the opacity. For example:
python
def update_images(self, prev_imgs=None, next_imgs=None):
# Existing code to set pixmaps...
# Optionally, highlight the central image
central_label = self.image_containers[self.preview_images_count // 2]
central_label.setPixmap(QPixmap.fromImage(QImage_from_np(self.image_list[self.current_index])))
opacity_effect = QGraphicsOpacityEffect()
opacity_effect.setOpacity(1.0) # Fully opaque for the current image
central_label.setGraphicsEffect(opacity_effect)
# Reduce opacity for other images handled in the loop above
Complete Integration Example
Here's how you can put everything together in a single script. This example assumes that you have a list of image file paths.
python
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import (
QApplication, QLabel, QMainWindow, QMessageBox, QVBoxLayout,
QWidget
)
import numpy as np
# Include your existing imports and classes here
# ... (Your existing code)
# Example QImage_from_np function
def QImage_from_np(arr):
if arr is None:
return QImage()
height, width, channel = arr.shape
bytes_per_line = 3 * width
return QImage(arr.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
# ImageViewer class as defined above
# ... (As defined in Step 1)
# MainWindow class as defined above
# ... (As defined in Step 2)
# Main application entry
def main():
app = QApplication(sys.argv)
# Example image list (replace with your actual image paths or numpy arrays)
image_list = [
'path/to/image1.jpg',
'path/to/image2.jpg',
'path/to/image3.jpg',
'path/to/image4.jpg',
'path/to/image5.jpg',
]
window = MainWindow(image_list=image_list)
window.resize(800, 600)
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Additional Considerations
Image Loading: Ensure that the images are loaded correctly, whether they are file paths or numpy arrays. Adjust the display_image method accordingly.
Error Handling: Add error handling for scenarios like missing images or unsupported formats.
Performance: For large images, consider optimizing the display_image method to handle scaling efficiently.
Focus Handling: If other widgets in your application can take focus, ensure that ImageViewer regains focus when necessary to continue receiving key events.
Custom Shortcuts: You can integrate the arrow keys and wheel events with other parts of your application (like toolbar buttons) for more cohesive navigation.
Summary
By overriding the keyPressEvent and wheelEvent methods in your main image display widget (ImageViewer), you can effectively add keyboard and mouse wheel navigation to switch between images. Integrating this with your ImagePreviewSequenceBar ensures that users have a coherent and interactive browsing experience.
Feel free to adjust the specifics based on your actual application architecture and requirements.