我有一个检测keyPressEvent的方法,然后想调用对话框来检索文件(后来添加其他选项以显示某些文件或全部)。
但是我必须扎根,使某些对象具有全局性,例如
pic_as_label = QLabel(self)
请随时指出其他问题。尽管我知道全局格式是错误的,但是这是可行的。
import sys, os
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QDesktopWidget, QFileDialog, QAction, QTextEdit
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import Qt
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Image Viewer'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()
def openFileNameDialog(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()
openFile = QAction(QIcon('open.png'), 'Open', self)
openFile.setShortcut('Ctrl+O')
openFile.setStatusTip('Open new File')
openFile.triggered.connect(self.showDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('File dialog')
self.show()
def initUI(self):
global desktop
global ScrWidth
global ScrHeight
global pic_as_label
desktop = os.environ['USERPROFILE'] + '\Desktop'
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.setAutoFillBackground
ScrWidth=QDesktopWidget().availableGeometry().width()
ScrHeight=QDesktopWidget().availableGeometry().height()
#pallete color Black
p = self.palette()
p.setColor(self.backgroundRole(), Qt.black)
self.setPalette(p)
self.resize(ScrWidth, ScrHeight)
pic_as_label = QLabel(self)
pixmap = QPixmap("image.jpg")
pixmap = pixmap.scaled (ScrWidth, ScrHeight, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation)
pic_as_label.move(((ScrWidth-pixmap.width())/2), ((ScrHeight-pixmap.height())/2))
pic_as_label.setPixmap(pixmap)
self.show()
def get_pic_name(self):
#Open File dialogue
fname = (QFileDialog.getOpenFileName(self, 'Open file',desktop, 'Images (*.jpg)'))[0]
App.setWindowTitle(self, os.path.split(fname)[1])
return fname
def display_photo(self, fname,w,h):
pixmap = QPixmap(fname)
pixmap = pixmap.scaled (w, h, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation)
pic_as_label.move(((w-pixmap.width())/2), ((h-pixmap.height())/2))
pic_as_label.setPixmap(pixmap)
def keyPressEvent(self,k):
if k.key() == Qt.Key_O:
fname = App.get_pic_name(self)
if fname:
picture_dir=os.path.split(fname)[0]
App.setWindowTitle(self, picture_dir)
App.display_photo(self,fname,ScrWidth, ScrHeight)
if k.key() == Qt.Key_X:
sys.exit(0)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())