您现在的位置是:网站首页 > 博客日记 >

Pyside2在搜索框内侧添加搜索图标

作者:YXN-python 阅读量:20 发布日期:2024-10-26

import sys
from PySide2.QtCore import QSize, Qt, QRect, Signal
from PySide2.QtGui import QPainter, QIcon, QCursor
from PySide2.QtWidgets import QApplication, QLineEdit, QWidget


class SearchLineEdit(QLineEdit):
    search_val = Signal(str)

    def __init__(self, parent=None):
        super(SearchLineEdit, self).__init__(parent)
        self.setPlaceholderText("请输入搜索值")
        self.setToolTip('搜索')
        self.setFixedSize(300, 35)
        self.setStyleSheet("border: 1px solid #ccc; border-radius: 5px; padding-right: 30px;")

        self.search_icon = QIcon("../img/search.ico")
        self.icon_size = QSize(16, 16)

    def paintEvent(self, event):
        super(SearchLineEdit, self).paintEvent(event)

        if not self.search_icon.isNull():
            rect = self.rect()
            icon_rect = QRect(
                rect.right() - self.icon_size.width() - 5,
                (rect.height() - self.icon_size.height()) // 2,
                self.icon_size.width(),
                self.icon_size.height()
            )

            painter = QPainter(self)
            self.search_icon.paint(painter, icon_rect)

    def mousePressEvent(self, event):
        if self.is_icon_clicked(event.pos()):
            self.on_search_icon_clicked()
        else:
            super(SearchLineEdit, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.is_icon_clicked(event.pos()):
            self.setCursor(QCursor(Qt.PointingHandCursor))
        else:
            self.setCursor(QCursor(Qt.IBeamCursor))
        super(SearchLineEdit, self).mouseMoveEvent(event)

    def leaveEvent(self, event):
        self.setCursor(QCursor(Qt.IBeamCursor))
        super(SearchLineEdit, self).leaveEvent(event)

    def is_icon_clicked(self, pos):
        rect = self.rect()
        icon_rect = QRect(
            rect.right() - self.icon_size.width() - 5,
            (rect.height() - self.icon_size.height()) // 2,
            self.icon_size.width(),
            self.icon_size.height()
        )
        return icon_rect.contains(pos)

    def on_search_icon_clicked(self):
        self.search_val.emit(self.text().strip())


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setFixedSize(400, 100)

        self.search_line_edit = SearchLineEdit(self)
        self.search_line_edit.move(10, 10)
        self.search_line_edit.search_val.connect(self.on_search)

    def on_search(self, text):
        print(f"搜索值: {text}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

效果图:

YXN-python

2024-10-26