📌  相关文章
📜  PyQt5 – 鼠标悬停时 lineedit 部分的边框颜色不同(对于不可编辑的组合框)(1)

📅  最后修改于: 2023-12-03 15:04:00.656000             🧑  作者: Mango

PyQt5 – 鼠标悬停时 lineedit 部分的边框颜色不同(对于不可编辑的组合框)

在 Pyqt5 中,可以通过添加样式表来控制部件的外观,包括线条和边框的颜色、粗细和样式。下面的示例演示了如何在鼠标悬停时更改 QLineEdit 的部分边框颜色,特别是用于不可编辑的组合框的情况。

安装 Pyqt5

在开始之前,请确保您已经安装了 Pyqt5 和其其他依赖项。如果您还没有安装它,可以使用以下命令:

pip install pyqt5
创建 QLineEdit 和 QComboBox 对象

首先,我们需要在 Python 中创建 QLineEdit 和 QComboBox 对象。以下是创建对象的代码片段:

from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QComboBox
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.le = QLineEdit(self)
        self.le.setGeometry(10, 10, 200, 30)

        self.cb = QComboBox(self)
        self.cb.setGeometry(10, 50, 200, 30)
        self.cb.setEditable(False)
        self.cb.addItems(["Item 1", "Item 2", "Item 3"])

        self.setGeometry(300, 300, 400, 150)
        self.setWindowTitle('Example')
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

在上面的代码中,我们创建了一个名为 Example 的小部件,并在其中添加了一个 QLineEdit 和一个 QComboBox。注意,我们将 QComboBox 设置为不可编辑的,以便用户无法更改其文本。

更改样式表以更改外观

接下来,我们将通过添加样式表来更改 QLineEdit 的外观。

在 Pyqt5 中,可以使用 setStyleSheet() 方法来设置样式表。以下是设置样式表的代码片段:

self.le.setStyleSheet("QLineEdit:hover:!disabled {border: 2px solid blue}")

该代码片段表示当用户将鼠标悬停在 QLineEdit 上时,将使用蓝色边框突出显示部件。在此代码中,我们使用了:hover伪类来指定只有在鼠标悬停时才应用此样式,而:!disabled则指定只有当部件可编辑时才应该应用此样式。由于我们的 QComboBox 是不可编辑的,因此我们需要使用此类选择器来排除不需要的部分。

可运行示例

以下是完整的 Python 代码,其中包含我们前面讨论的所有部分。可以将其复制并在 Python 中运行以查看效果。

from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QComboBox
import sys

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.le = QLineEdit(self)
        self.le.setGeometry(10, 10, 200, 30)
        self.le.setStyleSheet("QLineEdit:hover:!disabled {border: 2px solid blue}")

        self.cb = QComboBox(self)
        self.cb.setGeometry(10, 50, 200, 30)
        self.cb.setEditable(False)
        self.cb.addItems(["Item 1", "Item 2", "Item 3"])

        self.setGeometry(300, 300, 400, 150)
        self.setWindowTitle('Example')
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

现在,当您将鼠标悬停在 QLineEdit 上面时,您会注意到其部分边框的颜色发生了变化,而对于 QComboBox 而言,其边框则不会改变。