pyqt5 c4

本文详细介绍了PyQt5中的各种窗口类型,如MainWindow、Dialog以及Widget,还涵盖了常见的控件,如按钮、文本框、标签、滑动条、对话框等的使用方法和属性,包括它们的布局、信号与槽、事件处理等特性。
摘要由CSDN通过智能技术生成

窗口类型

MainWindow有菜单栏、工具栏、状态栏、标题栏等

Dialog 对话框窗口,用来执行短期任务。可以是模态 或 非模态。

Widget可以作为顶层窗口,也可以嵌入到其他窗口

MainWindow继承自Widget

MainWindow不能用setLayout(),因为他有自己的布局。可以用setCentralWidget

QMainWindow

QWidget

QObject->QWidget->QMainWindow

窗口 = 客户区client area + 标题栏 + 四周边框

常用的坐标、位置、大小等函数 见P130

import sys
from PyQt5.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)
window = QWidget()
window.resize(300, 200)
window.move(250, 150)
window.setWindowTitle('Hello PyQt5')
window.show()
sys.exit(app.exec_())    	#若app运行成功,则exec_返回0,否则非0
#sys.exit可以确保程序完整地结束,这种情况下会记录程序是如何退出的

	def initUI(self):
		QToolTip.setFont(QFont('SansSerif', 10))
		self.setToolTip('这是一个<b>气泡提示</b>')

鼠标悬停时出现的气泡提示里 中文无法正常显示,是因为SansSerif字体不支持中文

QLabel

QWidget->QFrame->QLabel

用途很多,作为一个占位符 他可以作图片、gif、纯文本、链接、或富文本

文本框控件

QlineEdit        单行文本

QTextEdit        多行文本

setEchoMode()可以设置文本的显示格式,如不显示文本 等方便保密

		# 设置显示效果
		pNormalLineEdit.setEchoMode(QLineEdit.Normal)
		pNoEchoLineEdit.setEchoMode(QLineEdit.NoEcho)	#什么都不显示
		pPasswordLineEdit.setEchoMode(QLineEdit.Password)	#黑点代替
		pPasswordEchoOnEditLineEdit.setEchoMode(QLineEdit.PasswordEchoOnEdit)

也可以设置成掩码,如要求填入 固定格式的序列号 等

		pLicenseLineEdit.setInputMask(">AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#")

setValidator()文本验证器

from PyQt5.QtGui import QIntValidator ,QDoubleValidator  , QRegExpValidator
from PyQt5.QtCore import QRegExp

QDoubleValidator.setRange()有bug         setRange not work

QTextEdit还可以显示html

按钮类控件

所有的按钮的基类都是QAbstractButton. QAbstractButton是抽象类,不能被实例化,我们用的都是其子类。

QAbstractButton提供以下 状态和信号

 QPushButton

 setDefault()当窗口有多个按钮时,光标会在setDefault(True)的按钮上

按钮加快捷键+&

		self.btn1 = QPushButton("Button1")
		self.btn1.setCheckable(True)		#启用按钮“长期变色”功能,仅仅是 启用这个功能,按钮还是处于无色(unCkecked)的状态。
		#set True的按钮,单次点击后会变色(Checked),并保持,再点一次变回原状(无色unCkecked);
		#set False的按钮(默认),只有在鼠标按下的时候才会变色(Checked),鼠标弹起 即恢复原状(无色unCkecked)。
		#isChecked()即记录 当前按钮是否处于 变色状态。
		print(self.btn1.isChecked())		#unChecked
		self.btn1.toggle()		#toggle仅仅切换 变色状态,和isDown()等状态无关。
		#所以当setCheckable(False)时,toggle根本没用。
		print(self.btn1.isChecked())		#Checked
		self.btn1.clicked.connect(lambda:self.whichbtn(self.btn1) )	#clicked的瞬间,按钮的Checked就发生变化,然后才是信号与槽

		self.btn2.setIcon(QIcon(QPixmap("./images/python.png")))

#		self.btn3.setEnabled(False)
		self.btn3.setAutoRepeat(True)        #长按一直触发clicked
		self.btn3.clicked.connect(self.btnstate)

QRadioButton

在同一个组合里时,一次只能选择一个。如果需要多个独占的按钮组合,可以把他们放在QGroupBox或QButtonGroup

		self.btn1 = QRadioButton("Button1")
		self.btn1.setChecked(True)    #默认已选btn1
		self.btn1.toggled.connect(lambda:self.btnstate(self.btn1))
        
		self.btn2 = QRadioButton("Button2")
		self.btn2.toggled.connect(lambda:self.btnstate(self.btn2))

		self.btn3 = QRadioButton("Button3")
		self.btn3.toggled.connect(lambda:self.btnstate(self.btn3))

	def btnstate(self,btn):
		if btn.text()=="Button1":
			if btn.isChecked() == True:
				print( btn.text() + " is selected" )
			else:
				print( btn.text() + " is deselected" )

btn1 btn2 btn3 在同一组内,如果一直不选btn3,则btn3的toggled永远不会被触发

QCheckBox

checkbox可以有三态

 第三态表示:没有变化。        通过setTristate()启用第三态,并用checkState()查询当前状态。

		groupBox = QGroupBox("Checkboxes")
		groupBox.setFlat( False )   #False有包围,True没有包围
		
		layout = QHBoxLayout()
        
		self.checkBox1= QCheckBox("&Checkbox1")
		self.checkBox1.setChecked(True)    #初始已勾选
		self.checkBox1.stateChanged.connect( lambda:self.btnstate(self.checkBox1) )    #toggled也行
        
		self.checkBox2 = QCheckBox("Checkbox2")
		self.checkBox2.toggled.connect( lambda:self.btnstate(self.checkBox2) )    #stateChanged也行

		self.checkBox3 = QCheckBox("tristateBox")
		self.checkBox3.setTristate(True)
		self.checkBox3.setCheckState(Qt.PartiallyChecked )		
		self.checkBox3.stateChanged.connect( lambda:self.btnstate(self.checkBox3) )
#		self.checkBox3.toggled.connect( lambda:self.btnstate(self.checkBox3) )    #最好不要

		layout.addWidget(self.checkBox1)
		layout.addWidget(self.checkBox2)
		layout.addWidget(self.checkBox3)
		groupBox.setLayout(layout)
        
		mainLayout = QVBoxLayout()
		mainLayout.addWidget(groupBox)
		
		self.setLayout(mainLayout)

	def btnstate(self,btn ):
		chk1Status = self.checkBox1.text()+", isChecked="+  str( self.checkBox1.isChecked() ) + ', chekState=' + str(self.checkBox1.checkState())   +"\n"		 
		chk2Status = self.checkBox2.text()+", isChecked="+  str( self.checkBox2.isChecked() ) + ', checkState=' + str(self.checkBox2.checkState())   +"\n"	
		chk3Status = self.checkBox3.text()+", isChecked="+  str( self.checkBox3.isChecked() ) + ', checkState=' + str(self.checkBox3.checkState())   +"\n"			
		print(chk1Status + chk2Status + chk3Status )

2态框用stateChanged或toggled作为信号都可以,3态框最好用stateChanged,toggled会导致checkState的值只有01,没有2

QComboBox

		layout = QVBoxLayout()
        
		self.lbl = QLabel("" )  
         
		self.cb = QComboBox()
		self.cb.addItem("C")
		self.cb.addItem("C++")
		self.cb.addItems(["Java", "C#", "Python"])
		self.cb.currentIndexChanged.connect(self.selectionchange)
        
		layout.addWidget(self.cb)
		layout.addWidget(self.lbl )
		self.setLayout(layout)
                                    
	def selectionchange(self,i):
		self.lbl.setText( self.cb.currentText() )
		self.lbl.adjustSize()    #Adjusts the size of the widget to fit its contents.
		
		print( "Items in the list are :" )
		for count in range(self.cb.count()):
			print( 'item'+str(count) + '='+ self.cb.itemText(count) )
			print( "Current index",i,"selection changed ",self.cb.currentText() )

QSpinBox

QAbstractSponBox->QSpinBox & QDoubleSpinBox        一个处理整理 一个处理浮点数

		self.l1=QLabel("current value:")
		self.l1.setAlignment(Qt.AlignCenter)
        
		self.sp = QSpinBox()
		self.sp.setSingleStep( 3 ) 
        
		self.sp.valueChanged.connect(self.valuechange)
		      
	def valuechange(self):	
		self.l1.setText("current value:" + str(self.sp.value()) )

默认范围0-99,默认步长1

QSlider

有时候 滑动条 比spinbox更方便

self.sl = QSlider(Qt.Horizontal)
self.sl = QSlider(Qt.Vertical)

 

		self.sl = QSlider(Qt.Horizontal)
        #设置最小值
		self.sl.setMinimum(10)
		#设置最大值
		self.sl.setMaximum(50)
		# 步长
		self.sl.setSingleStep(3)    #步长只对滚轮有效,对点击无限制。
		#由于 用户自身系统是有设置滚轮步长的,所以实际的数值增长 = 系统步长* setSingleStep
		# 设置当前值
		self.sl.setValue(20)
		# 刻度位置,刻度在下方
		self.sl.setTickPosition(QSlider.TicksBelow)
        # 设置刻度间隔
		self.sl.setTickInterval(5)
        
		self.sl.valueChanged.connect(self.valuechange)

对话类 控件

QDialog

QDialog — Qt for Python

A dialog window is a top-level window mostly used for short-term tasks and brief communications with the user. QDialogs may be modal or modeless. QDialogs can provide a return value , and they can have default buttons . QDialogs can also have a QSizeGrip in their lower-right corner, using setSizeGripEnabled() . Dialog窗口也是可以调整大小的

Note that QDialog (and any other widget that has type Qt::Dialog ) uses the parent widget slightly differently from other classes in Qt. A dialog is always a top-level widget, but if it has a parent, its default location is centered on top of the parent’s top-level widget (if it is not top-level itself). It will also share the parent’s taskbar entry. 对话框始终是顶级小部件,但如果它有父级,则其默认位置位于父级顶级小部件的顶部(如果它本身不是顶级小部件)。它还将共享父母的任务栏条目。

Use the overload of the setParent() function to change the ownership of a QDialog widget. This function allows you to explicitly set the window flags of the reparented widget; using the overloaded function will clear the window flags specifying the window-system properties for the widget (in particular it will reset the Dialog flag).

Modal Dialogs

modal dialog is a dialog that blocks input to other visible windows in the same application. Dialogs that are used to request a file name from the user or that are used to set application preferences are usually modal. Dialogs can be application modal (the default) or window modal .

When an application modal dialog is opened, the user must finish interacting with the dialog and close it before they can access any other window in the application. 用户必须完成与对话框的交互并关闭它,然后才能访问应用程序中的任何其他窗口

Window modal dialogs only block access to the window associated with the dialog, allowing the user to continue to use other windows in an application. 只阻止访问与对话框关联的窗口,允许用户继续使用应用程序中的其他窗口

The most common way to display a modal dialog is to call its exec() function. When the user closes the dialog, exec() will provide a useful return value . To close the dialog and return the appropriate value, you must connect a default button, e.g. an OK button to the accept() slot and a Cancel button to the reject() slot. Alternatively, you can call the done() slot with Accepted or Rejected .

An alternative is to call setModal (true) or setWindowModality() , then show() . Unlike exec() , show() returns control to the caller immediately. Calling setModal (true) is especially useful for progress dialogs, where the user must have the ability to interact with the dialog, e.g. to cancel a long running operation. If you use show() and setModal (true) together to perform a long operation, you must call processEvents() periodically during processing to enable the user to interact with the dialog. (See QProgressDialog .)

Modeless Dialogs

modeless dialog is a dialog that operates independently of other windows in the same application. Find and replace dialogs in word-processors are often modeless to allow the user to interact with both the application’s main window and with the dialog.

Modeless dialogs are displayed using show() , which returns control to the caller immediately.

If you invoke the show() function after hiding a dialog, the dialog will be displayed in its original position. This is because the window manager decides the position for windows that have not been explicitly placed by the programmer. To preserve the position of a dialog that has been moved by the user, save its position in your closeEvent() handler and then move the dialog to that position, before showing it again.

		self.btn.clicked.connect(self.showdialog)  
                
	def showdialog(self ):
		dialog = QDialog()
		btn = QPushButton("ok", dialog )
		btn.move(50,50)
		dialog.setWindowTitle("Dialog")
		dialog.setWindowModality(Qt.WindowModal)    
		dialog.exec_()

书本给的这个范例并不好。        setWindowModality(Qt.NonModal)和(Qt.ApplicationModal)时,父窗口都是锁定的

ApplicationModal锁定是正常实现了功能,但NonModal也锁定就很奇怪了

python - pyqt non-modal dialog always modal - Stack Overflow

When you create a nonmodal window, you must provide a parent QWidget in the instantiation of the QDialog class. Then, instead of using QDialog.exec_(), use QDialog.show(). This shows the nonmodal window but allows the original parent to keep running, in a sense. Using exec_() will always result in a modal window, even if you set it to nonmodal.

QDialog — Qt for Python

QMessageBox

P174

QInputBox        

几个预设好的 用来获取 整数、浮点数、文本、下拉列表选项 的交互框。        这样我们就不用自己在一个个组控件、写验证器。        虽然比较简陋

QFontDialog        字体设置

		self.fontButton .clicked.connect(self.getFont)

	def getFont(self):
		font, ok = QFontDialog.getFont()
		if ok:
			self.fontLineEdit .setFont(font)

QFileDialog        文件寻找

		self.le = QLabel("")
        
		self.contents = QTextEdit()

	def getfile(self):
		fname, _  = QFileDialog.getOpenFileName(self, 'Open file', 'c:\\',"Image files (*.jpg *.gif)")    
		#print(str(fname))    #getOpenFileName返回的文件名称是 带有路径的
		self.le.setPixmap(QPixmap(fname))
	
	def getfiles(self):
		dlg = QFileDialog()
		dlg.setFileMode(QFileDialog.AnyFile)
		dlg.setFilter( QDir.Files  )    #可以多个QDir.进行位或
	
		if dlg.exec_():
			filenames= dlg.selectedFiles()    #同上,带有路径
			#print(str(filenames))
			f = open(filenames[0], 'r', encoding='utf-8') 
            
			with f:
				data = f.read()
				self.contents.setText(data) 

窗口绘图类 控件

QPainter提供较低级别的绘制功能

draw必须要在QPainter的begin 和 end之间

class Drawing(QWidget):
	def __init__(self,parent=None):
        ...
         
	def paintEvent(self,event):		#paintEvent在app.exec_()后自动执行
		#time.sleep(5)
		painter = QPainter(self)        
		painter.begin(self)
        # 自定义的绘画方法
		self.drawText(event, painter)
		painter.end()
		print('ha')

	def drawText(self, event, qp):
        # 设置笔的颜色
		qp.setPen( QColor(168, 34, 3) )
        # 设置字体
		qp.setFont( QFont('SimSun', 20))
        # 画出文本
		qp.drawText(event.rect(), Qt.AlignCenter, self.text)
#QtGui.QPaintEvent.rect()	Returns the rectangle that needs to be updated.
		
if __name__ == "__main__":  
	app = QApplication(sys.argv) 
	demo = Drawing()
	print(1)
#	time.sleep(5)
	demo.show()
	print(2)
	#time.sleep(5)
	print(3)
	sys.exit(app.exec_())
	def paintEvent(self, event):
		qp = QPainter()
		qp.begin(self)
		# 自定义画点方法
		self.drawPoints(qp)
		qp.end()
		
	def drawPoints(self,  qp):
		qp.setPen( Qt.red)
		size = self.size()
		
		for i in range(1000):
			# [-100, 100]两个周期的正弦函数图像
			x = 100 *(-1+2.0*i/1000)+ size.width()/2.0
			y = -50 * math.sin((x - size.width()/2.0)*math.pi/50) + size.height()/2.0
			qp.drawPoint(x, y)
	def paintEvent(self, e): 
		qp = QPainter()
		qp.begin(self)
		self.drawLines(qp)
		qp.end()

	def drawLines(self, qp):
		pen = QPen(Qt.black, 2, Qt.SolidLine)

		qp.setPen(pen)
		qp.drawLine(20, 40, 250, 40)

		pen.setStyle(Qt.DashLine)
		qp.setPen(pen)
		qp.drawLine(20, 80, 250, 80)

		pen.setStyle(Qt.DashDotLine)
		qp.setPen(pen)
		qp.drawLine(20, 120, 250, 120)

		pen.setStyle(Qt.DotLine)
		qp.setPen(pen)
		qp.drawLine(20, 160, 250, 160)

		pen.setStyle(Qt.DashDotDotLine)
		qp.setPen(pen)
		qp.drawLine(20, 200, 250, 200)

		pen.setStyle(Qt.CustomDashLine)
		pen.setDashPattern([1, 4, 5, 4, 5, 4])    #列表元素数 必须是偶数
		qp.setPen(pen)
		qp.drawLine(20, 240, 250, 240)
	def paintEvent(self, e): 
		qp = QPainter()
		qp.begin(self)
		self.drawLines(qp)
		qp.end()

	def drawLines(self, qp): 
		brush = QBrush(Qt.SolidPattern)
		qp.setBrush(brush)
		qp.drawRect(10, 15, 90, 60)

		brush = QBrush(Qt.Dense1Pattern)
		qp.setBrush(brush)
		qp.drawRect(130, 15, 90, 60)

		brush = QBrush(Qt.Dense2Pattern)
		qp.setBrush(brush)
		qp.drawRect(250, 15, 90, 60)

		brush = QBrush(Qt.Dense3Pattern)
		qp.setBrush(brush)
		qp.drawRect(10, 105, 90, 60)

		brush = QBrush(Qt.DiagCrossPattern)
		qp.setBrush(brush)
		qp.drawRect(10, 105, 90, 60)

		brush = QBrush(Qt.Dense5Pattern)
		qp.setBrush(brush)
		qp.drawRect(130, 105, 90, 60)

		brush = QBrush(Qt.Dense6Pattern)
		qp.setBrush(brush)
		qp.drawRect(250, 105, 90, 60)

		brush = QBrush(Qt.HorPattern)
		qp.setBrush(brush)
		qp.drawRect(10, 195, 90, 60)

		brush = QBrush(Qt.VerPattern)
		qp.setBrush(brush)
		qp.drawRect(130, 195, 90, 60)

		brush = QBrush(Qt.BDiagPattern)
		qp.setBrush(brush)
		qp.drawRect(250, 195, 90, 60)

QPixmap用于图像显示,可以加载到控件中(如 标签、按钮等)

能读取几乎所有图片类型

	lab1 = QLabel()
	lab1.setPixmap(QPixmap("./images/python.jpg"))

拖拽 与 剪贴板

为了方便用户,复制 或 移动对象 可以通过拖拽来完成。

很多控件都是支持拖拽的,前提是XXX.setDragEnabled(True)。然后,控件还要响应 拖拽事件,以便存储所拖拽的 数据。

class Combo(QComboBox):

	def __init__(self, title, parent):
		super(Combo, self).__init__( parent)
		self.setAcceptDrops(True)	#接受别的对象拖入combobox
		
	def dragEnterEvent(self, e):
		print( e)				#<PyQt5.QtGui.QDragEnterEvent object at
		if e.mimeData().hasText():
			e.accept()
		else:
			e.ignore() 	#ignore则 松开鼠标时不会触发dropEvent

	def dropEvent(self, e):
		self.addItem(e.mimeData().text()) 
		
class Example(QWidget):
	def __init__(self):
		super(Example, self).__init__()
		self.initUI()

	def initUI(self):
		lo = QFormLayout()
		lo.addRow(QLabel("请把左边的文本拖拽到右边的下拉菜单中"))
        
		#添加控件
		edit = QLineEdit()
		edit.setDragEnabled(True)
		
		com = Combo("Button", self)
		lo.addRow(edit,com)
        
		self.setLayout(lo)

 

 QClipboard

提供对系统剪贴板的访问。        QApplication都有静态方法clipboard(),他返回一个剪贴板对象,任何的mimedata都可以复制或粘贴到剪贴板

	def copyText(self):
		clipboard = QApplication.clipboard()	#返回对剪贴板对象
		clipboard.setText("I've been clipped!")
	
	def pasteText(self):
		clipboard = QApplication.clipboard()
		self.textLabel.setText(clipboard.text())
	
	def copyImage(self):
		clipboard = QApplication.clipboard()
		clipboard.setPixmap(QPixmap(os.path.join(
		os.path.dirname(__file__), "./images/python.png")))
	
	def pasteImage(self):
		clipboard = QApplication.clipboard()
		self.imageLabel.setPixmap(clipboard.pixmap())
	
	def copyHtml(self):
		mimeData = QMimeData()
		mimeData.setHtml("<b>Bold and <font color=red>Red</font></b>")
		clipboard = QApplication.clipboard()
		clipboard.setMimeData(mimeData)
	
	def pasteHtml(self):
		clipboard = QApplication.clipboard()
		mimeData = clipboard.mimeData()
		if mimeData.hasHtml():
			self.textLabel.setText(mimeData.html())

###
clipboard.clear()#清空剪贴板

日历和时间

没什么好说的,轮子直接用就是了

日历

class CalendarExample( QWidget):
	def __init__(self):
		super(CalendarExample, self).__init__()
		self.initUI()
		
	def initUI(self): 
		self.cal =  QCalendarWidget(self)
		self.cal.setMinimumDate(QDate(1980, 1, 1))
		self.cal.setMaximumDate(QDate(3000, 1, 1))
		self.cal.setGridVisible(True)		#设置日历是否显示网格
		self.cal.move(20, 20)
		self.cal.clicked[QtCore.QDate].connect(self.showDate)	#发射QtCore.QDate信号
		
		self.lbl =  QLabel(self)
		#app初始化时显示当前日期
		date = self.cal.selectedDate()		#返回当前日期,app初始化时 默认选择在当前时间
		#用函数self.cal.setSelectedDate(".......")	可以设置任意时间
		self.lbl.setText(date.toString("yyyy-MM-dd dddd"))
		self.lbl.move(20, 300)
		
		self.setGeometry(100,100,400,350)
		self.setWindowTitle('Calendar 例子')
		
	def showDate(self, date): 
		self.lbl.setText(date.toString("yyyy-MM-dd dddd") )

日期 时间        QDateTimeEdit        QDateEdit        QTimeEdit        这种的只有一行,而不是日历

		vlayout = QVBoxLayout()
		
		dateTimeEdit = QDateTimeEdit(self)	#实例化时不指定则,值为2000-01-01 00:00:00
		dateTimeEdit2 = QDateTimeEdit(QDateTime.currentDateTime(), self)	#手动指定
		dateEdit = QDateTimeEdit(QDate.currentDate(), self)
		timeEdit = QDateTimeEdit(QTime.currentTime(), self)

		# 设置日期时间格式,不设置则使用默认格式
		dateTimeEdit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
		dateTimeEdit2.setDisplayFormat("yyyy/MM/dd HH-mm-ss")
		dateEdit.setDisplayFormat("yyyy.MM.dd")
		timeEdit.setDisplayFormat("HH:mm:ss")
		self.dateEdit = QDateTimeEdit(QDateTime.currentDateTime(), self)
		self.dateEdit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        # 设置最小日期
		self.dateEdit.setMinimumDate(QDate.currentDate().addDays(-365)) 
        # 设置最大日期
		self.dateEdit.setMaximumDate(QDate.currentDate().addDays(365)) 
		self.dateEdit.setCalendarPopup( True)	#弹出日历

		self.dateEdit.dateChanged.connect(self.onDateChanged)  		#三种信号
		self.dateEdit.dateTimeChanged.connect(self.onDateTimeChanged) 
		self.dateEdit.timeChanged.connect(self.onTimeChanged) 
		
		self.btn = QPushButton('获得日期和时间')  
		self.btn.clicked.connect(self.onButtonClick) 
        
		vlayout.addWidget( self.dateEdit )
		vlayout.addWidget( self.btn )
		self.setLayout(vlayout)   

	# 日期发生改变时执行		
	def onDateChanged(self , date):
		print(date)
	
	# 无论日期还是时间发生改变,都会执行
	def onDateTimeChanged(self , dateTime ):
		print(dateTime)
			
	# 时间发生改变时执行
	def onTimeChanged(self , time):
		print(time)			
	
	def onButtonClick(self ):      
		dateTime  = self.dateEdit.dateTime()
		# 最大日期
		maxDate = self.dateEdit.maximumDate() 
		# 最大日期时间
		maxDateTime = self.dateEdit.maximumDateTime() 
		# 最大时间
		maxTime = self.dateEdit.maximumTime() 
		# 最小日期
		minDate = self.dateEdit.minimumDate() 
		# 最小日期时间
		minDateTime = self.dateEdit.minimumDateTime() 
		# 最小时间	
		minTime = self.dateEdit.minimumTime() 
		 
		print('\n选择日期时间'  )  	
		print('dateTime=%s' % str(dateTime) ) 
		print('maxDate=%s' % str(maxDate) ) 
		print('maxDateTime=%s' % str(maxDateTime) ) 
		print('maxTime=%s' % str(maxTime) ) 
dateTimeEdit.setCalendarPopup( True)
dateEdit.setCalendarPopup( True)
timeEdit.setCalendarPopup( True)    #不生效

只有QDateTimeEdit、QDateEdit可以弹出日历,QTimeEdit不起作用

菜单栏、工具栏、状态栏

		bar = self.menuBar()
        
		file = bar.addMenu("File")	#return QMenu Object
		file.addAction("New")
		save = QAction("Save",self)
		save.setShortcut("Ctrl+S")
		file.addAction(save)

		edit = file.addMenu("Edit")	#QMenu Object里可以继续添加QMenu Object,这是第二级QMenu Object
		edit.addAction("copy")
		edit.addAction("paste")
		
		quit = QAction("Quit",self)
		file.addAction(quit)

		file.triggered[QAction].connect(self.processtrigger) 	#触发信号的QAction将作为参数传给processtrigger()
        
		self.setLayout(layout)
		self.setWindowTitle("menu 例子")
		self.resize(350,300)
		
	def processtrigger(self,q):
		print( q.text()+" is triggered" )
#		layout = QVBoxLayout()
		tb = self.addToolBar("File")
		new = QAction(QIcon("./images/new.png"),"new",self)
		tb.addAction(new)
		open = QAction(QIcon("./images/open.png"),"open",self)
		tb.addAction(open)
		save = QAction(QIcon("./images/save.png"),"save",self)
		tb.addAction(save)
		tb.actionTriggered[QAction].connect(self.toolbtnpressed)
#		self.setLayout(layout)
           	
	def toolbtnpressed(self,a):
		print("pressed tool button is",a.text() )
		bar = self.menuBar()
		file = bar.addMenu("File")
		file.addAction("show")
		file.triggered[QAction].connect(self.processTrigger)
#		self.setCentralWidget(QTextEdit())
		self.statusBar= QStatusBar() 
		self.setStatusBar(self.statusBar)

	def processTrigger(self,q):
		if (q.text()=="show"):
			self.statusBar.showMessage(q.text()+" 菜单选项被点击了",5000)
       # 创建一个放置图像的QLabel对象imageLabel,并将该QLabel对象设置为中心窗体。 
		self.imageLabel=QLabel()  
		self.imageLabel.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored)  
		self.setCentralWidget(self.imageLabel)  

		self.image=QImage()  
		  
       # 创建菜单,工具条等部件 
		self.createActions()  
		self.createMenus()  
		self.createToolBars()  

       # 在imageLabel对象中放置图像
		if self.image.load("./images/screen.png"):  
			self.imageLabel.setPixmap(QPixmap.fromImage(self.image))  
			self.resize(self.image.width(),self.image.height())  
									
	def createActions(self):  
		self.PrintAction=QAction(QIcon("./images/printer.png"),self.tr("打印"),self)  
		self.PrintAction.setShortcut("Ctrl+P")  
		self.PrintAction.setStatusTip(self.tr("打印"))  
		self.PrintAction.triggered.connect(self.slotPrint) 

	def createMenus(self):  
		PrintMenu=self.menuBar().addMenu(self.tr("打印"))  
		PrintMenu.addAction(self.PrintAction)  

	def createToolBars(self):  
		fileToolBar=self.addToolBar("Print")  
		fileToolBar.addAction(self.PrintAction)  

	def slotPrint(self):  
       # 新建一个QPrinter对象 
		printer=QPrinter()  
       # 创建一个QPrintDialog对象,参数为QPrinter对象 
		printDialog=QPrintDialog(printer,self)  

		'''
       判断打印对话框显示后用户是否单击“打印”按钮,若单击“打印”按钮,
       则相关打印属性可以通过创建QPrintDialog对象时使用的QPrinter对象获得,
       若用户单击“取消”按钮,则不执行后续的打印操作。 
		''' 		
		if printDialog.exec_():  
           # 创建一个QPainter对象,并指定绘图设备为一个QPrinter对象。
			painter=QPainter(printer)  
			# 获得QPainter对象的视口矩形
			rect=painter.viewport()  
			# 获得图像的大小
			size=self.image.size()  
			# 按照图形的比例大小重新设置视口矩形
			size.scale(rect.size(),Qt.KeepAspectRatio)  
			painter.setViewport(rect.x(),rect.y(),size.width(),size.height())  
			# 设置QPainter窗口大小为图像的大小
			painter.setWindow(self.image.rect()) 
			# 打印			
			painter.drawImage(0,0,self.image)  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值