python - 从按键事件设置小部件

标签 python python-3.x pyqt pyqt5

我正在尝试在按空格键时设置一个小部件。 我有一个包含 QLabel 的 QGridLayout。 我想在 QGridLayout 中根据您的坐标设置特定 Qlabel 的文本,但是当我从按键功能访问 QGridLayout 时,该变量为空。

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtCore import QSize    

class Position:
   def __init__(self, x, y):
      self.x = x
      self.y = y

class HelloWindow(QMainWindow):
    global gridLayout
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(640, 640))    
        self.setWindowTitle("Hello world") 

        centralWidget = QWidget(self)          
        self.setCentralWidget(centralWidget)   

        gridLayout = QGridLayout(self)
        gridLayout.setSpacing(0)  
        centralWidget.setLayout(gridLayout)  

        file_text = open("logic/file.txt", "r")
        file = file_text.read()
        file = file.replace("[(","")
        file = file.replace(")]","")
        file = file.replace("),(",";")
        positions = file.split(';')
        lista = []
        for pos in positions:
         coord = pos.split(',')
         temp = Position(int(coord[0]),int(coord[1]))
         lista.append(temp)
        file_text.close()

        cont = 0
        for x in range(0, 9):
         for y in range(0, 9):
            if cont < 64:
               title = QLabel(str(cont+1), self) 
               title.setAlignment(QtCore.Qt.AlignCenter)
               title.setContentsMargins(0,0,0,0)
               title.setStyleSheet('QLabel {background-color: white; color: red; font-size: 24px; font-weight: bold}')
               if cont%2 == 0:
                  title.setStyleSheet('QLabel {background-color: black; color: red; font-size: 24px; font-weight: bold}')
               gridLayout.addWidget(title,lista[cont].x,lista[cont].y)
               cont += 1

    def keyPressEvent(self, event):
      if event.key() == QtCore.Qt.Key_Escape:
         self.close()
      if event.key() == QtCore.Qt.Key_Space:
         item = gridLayout.itemAtPosition(1,1)
         w = item.widget()
         w.setText("test")

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    sys.exit( app.exec_() )

下一节是测试

def keyPressEvent(self, event):
      if event.key() == QtCore.Qt.Key_Escape:
         self.close()
      if event.key() == QtCore.Qt.Key_Space:
         item = gridLayout.itemAtPosition(1,1)
         w = item.widget()
         w.setText("test")

我从您的坐标访问小部件以设置您的文本。

最佳答案

问题是由全局变量的误用引起的,每次使用它时都必须声明,在你的情况下:

class HelloWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        [...]
        global gridLayout
        gridLayout = QGridLayout(self)
        [...]

    def keyPressEvent(self, event):
      if event.key() == QtCore.Qt.Key_Escape:
         self.close()
      if event.key() == QtCore.Qt.Key_Space:
        global gridLayout
        item = gridLayout.itemAtPosition(1, 1)
        w = item.widget()
        w.setText("test")

一个更优雅的解决方案是将 gridLayout 声明为类的属性,为此你必须将 gridLayout 更改为 self.gridLayout所有情况:

class Position:
   def __init__(self, x, y):
      self.x = x
      self.y = y

class HelloWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(640, 640))    
        self.setWindowTitle("Hello world") 

        centralWidget = QWidget(self)          
        self.setCentralWidget(centralWidget)   
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setSpacing(0)  
        centralWidget.setLayout(self.gridLayout)  

        file_text = open("logic/file.txt", "r")
        file = file_text.read()
        file = file.replace("[(", "")
        file = file.replace(")]", "")
        file = file.replace("),(", ";")
        positions = file.split(';')
        lista = []
        for pos in positions:
            coord = pos.split(',')
            temp = Position(int(coord[0]), int(coord[1]))
            lista.append(temp)
        file_text.close()

        cont = 0
        for x in range(0, 9):
            for y in range(0, 9):
                if cont < 64:
                    title = QLabel(str(cont+1), self) 
                    title.setAlignment(QtCore.Qt.AlignCenter)
                    title.setContentsMargins(0, 0, 0, 0)
                    title.setStyleSheet('QLabel {background-color: white; color: red; font-size: 24px; font-weight: bold}')
                    if cont%2 == 0:
                       title.setStyleSheet('QLabel {background-color: black; color: red; font-size: 24px; font-weight: bold}')
                    self.gridLayout.addWidget(title, lista[cont].x, lista[cont].y)
                    cont += 1

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()
        if event.key() == QtCore.Qt.Key_Space:
            item = self.gridLayout.itemAtPosition(1, 1)
            w = item.widget()
            w.setText("test")

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    sys.exit(app.exec_())

关于python - 从按键事件设置小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43744118/

相关文章:

python - QThread 不发出完成信号

python - 使用 python 通过串行发送十六进制

Python用星号替换字符串的某些部分

python - CSV如何查找值并编辑其值

python-3.x - asyncio 以不同的间隔定期运行两个不同的函数

python - 如何使用 pyqt QFileDialog 将图像上传到 sqlite 数据库?

python - 如何使用vtk选择直线上的点?

python - 从不同的 pandas 行中获取元素的组合

Python 正则表达式在输出中搜索并打印 'apostrophes' (')

从 bash 运行的 python 多行命令