基本框架
class Window(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(200, 200, 400, 400)
self.setWindowTitle(窗口名称)
self.setWindowIcon(QIcon(图标路径))
#在这里面创建小组件
#创建QApplicaion,保存事件循环,每个应用程序只能有一个QApplication对象
#如果想要通过命令行来启动窗口,就可以传入命令行参数列表sys.argv,如果不想,则传入空列表[]
#通过命令行启动窗口 python xxx.py
app = QApplication(sys.argv)
#创建窗口对象
#窗口:保存应用程序的用户界面
window = Window()
#展示窗口,所有顶级组件都是窗口,它们没有父级组件或布局,默认不会显示,只有通过.show()才能显示
#不添加到父级组件或布局上的组件是不会显示到窗口上的
window.show()
#启动事件循环,代码不会运行到事件循环下面,除非你关闭窗口或停止事件循环
#任何按键或鼠标动作都是事件,应用程序会一直等待事件并进行处理
#在PyQt5则可以这样子:app.exec_()
sys.exit(app.exec())
布局
Layout
#创建QHBoxLayout对象
hbox = QHBoxLayout()
#创建组件
label1 = QLabel("This is label1", self)
label2 = QLabel("This is label2", self)
label3 = QLabel("This is label3", self)
#将组件添加到QHBoxLayout对象中
hbox.addWidget(label1)
hbox.addWidget(label2)
hbox.addWidget(label3)
#添加间距
hbox.addSpacing()
#预留空位
hbox.addStretch()
#将布局设置到主窗口
self.setLayout(hbox)
#QVBoxLayout跟QHBoxLayout只有名字不一样
#QGirdLayout栅格系统仅有添加方法不同,若中间有空位会挤掉
QGridLayout对象.addWidget(widgetElement, col, row)
#嵌套布局
QStackedLayout
Tab栏
form
列表
#创建列表对象
list_widget = QListWidget()
#添加元素
list_widget.insertItem(0, "Python")
list_widget.insertItem(1, "Java")
list_widget.insertItem(2, "JavaScript")
list_widget.insertItem(1, "Kotlin") #若该位置已存在元素,则会进行插队
#列表中的任何一项被点击都会触发事件
list_widget.clicked.connect(方法名)
表格
#创建表格对象
table_widget = QTableWidget()
#设置行
table_widget.setRowCount(3)
#设置列
table_widget.setColumnCount(5)
# 添加元素
table_widget.setItem(0, 0, QTableWidgetItem("Name"))
table_widget.setItem(0, 1, QTableWidgetItem("Emali"))
table_widget.setItem(0, 2, QTableWidgetItem("Phone"))
元素
属性设置
#窗口属性
#不透明度
windowElement.setWindowTitle(名称)
#窗口图标
windowElement.setWindowIcon(QIcon(图片路径))
#不透明度,0~1
windowElement.setWindowOpacity(0.5)
#字体
#如果是在qt5,则这么写: QFont.ExtraBold
element.setFont(QFont("Times", 14, ((QFont.Weight.ExtraBold))
#颜色
element.setStyleSheet("color:red")
#位置大小
element.setGeometry(x, y, width, height)
element.resize(width, height)
element.setFixedWidth(width)
element.setFixedHeight(height)
element.setFixedSize(width, height)
#图标
element.setIcon(QIcon(图标路径))
element.setIconSize(QSize(width, height))
element.setIconSize(width, height)
文本
element.setText(文本字符串)
主窗口
#QWidget
#QMainWindow
#QDialog
文本图像
文本
#创建Label对象
label = QLabel("helloPyQt6")
#设置文本,文本内容必须是字符串形式,若是数字需要强转为字符串类型W
label.setText("helloWorld")
#设置数字
label.setNum(200)
#设置文本位置
label.move(200, 200)
#清楚标签文本
label.clear()
图像
#创建QPixmap对象(QtGui库里面的)
pixmap = QPixmap(图片路径)
#将图片放入label标签中
label.setPixmap(pixmap)
动态图
#创建QMovie对象
movie = QMovie()
#将QMovie对象放到label中
label.setMovie(movie)
#设置播放速度,单位是什么呢?
movie.setSpeed(500)
#开始播放
movie.start()
QLCDNumber
class Window(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(200, 200, 700, 400)
self.setWindowTitle("Python PyQt6")
self.setWindowIcon(QIcon(图标路径))
timer = QTimer()
timer.timeout.connect(self.showLCD)
timer.start(1000)
self.showLCD()
def showLCD(self):
vbox = QVBoxLayout()
lcd = QLCDNumber()
lcd.setStylesheet("background:red")
vbox.addWidget(lcd)
#创建事件对象
time = QTime.currentTime()
text = time.toString("hh:mm")
#将文本显示到lcd上
lcd.display(text)
self.setLayout(vbox)
按钮菜单
按钮
#创建按钮对象
button = QPushButton("Button")
#绑定点击事件
button.clicked.conncet(方法名)
#创建菜单对象
menu = QMenu()
menu.addAction("Copy")
menu.addAction("Cut")
#为按钮绑定菜单
button.setMenu(menu)
#菜单添加选项
menu.addAction(icon, text)
#禁用按钮
button.setEnabled(Fasle)
单选框
#创建单选框对象
rad1 = QRadioButton("rad1")
#默认选中
rad1.setChecked(True)
#获取单选框的文本
value = rad1.text()
#获取单选框的值
value = rad1.isChecked
#为单选框绑定事件
rad1.toggled.connect(方法名) #绑定事件
sender().isChecked() #方法中接收单选框的状态
#为单选框分组
复选框
旋钮
#创建旋转按钮对象
spinbox = QSpinBox()
#双精度旋钮
doubleSpinBox = QDoubleSpinBox()
#获取旋钮的值
value = spinbox.value()
#值改变事件
spinbox.valueChanged.connect(方法名)
#编辑完成事件
doubleSpinBox.editingFinished.connect(方法名)
值改变信号
class UI(QWidget):
def __init__(self):
super().__init__()
uic.loadUi("DoubleSpinDemo.ui", self)
self.linePrice = self.findChild(QLineEdit, "lineEdit_price")
self.doublespin = self.findChild(QDoubleSpinBox, "doubleSpinBox")
self.lineResult = self.findChild(QLineEdit, "lineEdit_total")
#添加事件
self.doublespin.valueChanged.connect(self.spin_selected)
def spin_selected(self):
if self.linePrice.text() != 0:
price = int(self.linePrice.text())
totalPrice = self.doublespin.value() * price
self.lineResult.setText(str(totalPrice))
下拉菜单
#创建下拉菜单对象
combo = QComoBox()
#向下拉菜单中添加元素
combo.addItem("Option1")
combo.addItem("Option2")
combo.addItem("Option3")
combo.addItem("Option4")
#获取当前文本
item = combo.currentText()
#绑定元素改变事件
combo.currentTextChanged.connect(方法名)
字体、颜色、日期
取色器
#选择颜色
color = QColorDialog.getColor()
#判断选择的颜色是否有效
if color.isValid():
#将颜色设置到组件上
self.组件名称.setTextColor(color)
取字器
#选择字体
font, ok = QFontDialog.getFont()
#判断是否选择成功
if ok:
#将字体设置到组件上
self.组件名称.setFont(font)
字体菜单
#创建字体菜单对象
fontComboBox = QFontComboBox()
#获取当前字体
font = fontComboBox.itemText(fontComboBox.currentIndex())
#绑定字体修改事件
fontComboBox.currentFontChanged.connect(方法名)
日历编辑框
#有QDateEdit,QTimeEdit和QDateTimeEdit
#创建日历编辑框对象并传入当前时间
dateEdit = QDateTimeEdit(QDateTime.currentDateTime())
#设置可弹出日历进行日期选择,默认为False
dateEdit.setCalendarPopup(True)
#设置为不可编辑,也无法弹出日历
dateEdit.setEnabled(False)
#修改显示格式
dateEdit.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
#设置失效
dateEdit.setDisabled(True)
#设置可选择的最大日期和最小日期,还有时间,还有范围
dateEdit.setMinimumDate()
dateEdit.setMaximumDate()
#获取时间
dateEdit.dateTime()
日历组件
#创建日历对象
calendar = QCalendarWidget()
#添加网格界面
calendar.setGridVisible(True)
#设置可选日期,可选择的最大日期和最小日期,还有时间,还有范围
calendar.setDateRange()
#让日历选择某个时间
calendar.setSelectedDate(QDate.currentDate().addDays(10))
#设置每周从星期几开始
calendar.setFirstDayOfWeek(Qt.DayOfWeek.Sunday)
#绑定选择事件
calendar.selectionChanged.connect(方法名)
#获取选中的日期
dateSelected = calendar.selectedDate()
#将日期转换为字符串
date_string = str(dateSelected.toPyDate())
#获取当前日期
编辑
文本编辑
#创建QLineEdit对象
line_edit = QLineEdit()
#设置默认文本
line_edit.setText("这是默认的编辑文本")
#设置占位符
line_edit.setPlaceholderText("请输入")
#禁用编辑框
line_edit.setEnabled(False)
#设置为密码
line_edit.setEchoMode(QLineEdit.EchoMode.Password)
交互话框
#获取选项,返回所选内容和是否成功
# 第一个参数是窗口对象,第二个参数是方框标题,第三个参数是所选元素标题,第四个参数是 ,第五个参数是
country, ok = QInputDialog.getItem(self, "Input Dialog", "list of countries", ['Chinese', 'Japan'], 0, False)
#客户自己输入,返回客户输入内容和是否成功
# 第一个参数是窗口对象,第二个参数是方框标题,第三个参数是所选元素标题,第四个参数是 ,第五个参数是
country, ok = QInputDialog.getText(self, "Get Username", "Enter your name")
#获取数字,返回数字和是否成功
# 第一个参数是窗口对象,第二个参数是方框标题,第三个参数是所选元素标题,第四个参数是 ,第五个参数是
number, ok = QInputDialog.getInt(self, "Order Quantity", "Enter Quantity: ", 1, 2)
提示弹窗
# 第一个参数是窗口对象,第二个参数是话框标题,第三个参数是话框内容
#弹出警告框
QMessageBox.warning(self, "Waring", "This is a warning message")
#弹出消息框
QMessageBox.information(self, "Information", "This is a information message")
#弹出about框
QMessageBox.about(self, "About", "This is a about message")
滑块
#创建滑块对象
slider = QSlider()
#水平方向
slider.setOrientation(Qt.Orientation.Horizontal)
#竖直方向
#slider.setOrientation(Qt.Orientation.Vertical)
#设置刻度,可以通过修改TickPosition后的属性设置不同方向的刻度
slider.setTickPosition(QSlider.TickPosition.TicksBelow)
#设置间隔
slider.setTickInterval(20)
#设置最小值
slider.setMinimum(0)
#设置最大值
slider.setMaximum(100)
#刻度滑动事件
slider.valueChanged.connect(self.changed_slider)
#获取滑块值
value = slider.value()
几何图形
点
线
矩形
圆形
图表
折线图
条形图
堆叠柱形图
环形图
饼图
散点图
信号、插槽、事件
鼠标
#鼠标点击事件
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.label = QLabel("Click in this window")
self.setMouseTracking(True)
self.setCentralWidget(self.label)
#只有单击之后移动才能触发,除非将窗口的setMouseTracking设为True
def mouseMoveEvent(self, e):
self.label.setText("mouseMoveEvent")
def mousePressEvent(self, e):
self.label.setText("mousePressEvent")
def mouseReleaseEvent(self, e):
self.label.setText("mouseReleaseEvent")
def mouseDoubleClickEvent(self, e):
self.label.setText("mouseDoubleClickEvent")
#鼠标三个按键
#On right-handed mice the left and right button positions are reversed, i.e. pressing the right-most button will return `Qt.LeftButton`. This means you don't need to account for the mouse orientation in your code.
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.label = QPushButton("Click in this window", self)
self.label.resize(200, 200)
def mousePressEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton:
# handle the left-button press in here
self.label.setText("mousePressEvent LEFT")
elif e.button() == Qt.MouseButton.MiddleButton:
# handle the middle-button press in here.
self.label.setText("mousePressEvent MIDDLE")
elif e.button() == Qt.MouseButton.RightButton:
# handle the right-button press in here.
self.label.setText("mousePressEvent RIGHT")
def mouseReleaseEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton:
self.label.setText("mouseReleaseEvent LEFT")
elif e.button() == Qt.MouseButton.MiddleButton:
self.label.setText("mouseReleaseEvent MIDDLE")
elif e.button() == Qt.MouseButton.RightButton:
self.label.setText("mouseReleaseEvent RIGHT")
def mouseDoubleClickEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton:
self.label.setText("mouseDoubleClickEvent LEFT")
elif e.button() == Qt.MouseButton.MiddleButton:
self.label.setText("mouseDoubleClickEvent MIDDLE")
elif e.button() == Qt.MouseButton.RightButton:
self.label.setText("mouseDoubleClickEvent RIGHT")