[PyQt6] PartⅡ. ListWidget

ListWidget

一个表单

关键代码

self.list_widget.insertItem(0, "python") # addItem的话,没有row选项
self.list_widget.clicked.connect(self.item_clicked) # 绑定选中事件,发送signal,到slot,item_clicked

完整代码

from PyQt6.QtWidgets import QApplication, QWidget, QListWidget, QLabel, QHBoxLayout, QVBoxLayout
from PyQt6.QtGui import QIcon, QFont
from PyQt6.QtCore import Qt
import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(200, 200, 700, 400) # 设置窗口大小
        self.setWindowTitle("Python ListWidget")
        self.setWindowIcon(QIcon('python.png')) # 设置图片,没有的话不显示

        vbox = QVBoxLayout()

        self.list_widget = QListWidget() # 创建一个QListWidget对象

        self.list_widget.insertItem(0, "python") # addItem的话,没有row选项
        self.list_widget.insertItem(1, "java")
        self.list_widget.insertItem(2, "C++")
        self.list_widget.insertItem(3, "C#")
        self.list_widget.insertItem(4, "Kotlin")
        self.list_widget.setFont(QFont("Times", 15)) 
        self.list_widget.setStyleSheet("background-color: gray") 

        # connect signal
        self.list_widget.clicked.connect(self.item_clicked) # 绑定选中事件,发送signal,到slot,item_clicked
 
        self.label = QLabel("")
        self.label.setFont(QFont("Times", 15))

        vbox.addWidget(self.list_widget)
        vbox.addWidget(self.label)

        self.setLayout(vbox)

    def item_clicked(self):
        result = self.list_widget.currentItem()
        self.label.setText("You have selected: " + str(result.text()))


app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())

程序截图

posted @ 2022-05-24 16:17  deadright  阅读(117)  评论(0编辑  收藏  举报