2012-09-06 50 views
-1

如何在PyQt4中执行与this youtube video tutorial中的功能相同的功能。在视频教程中重现功能

有一个代码,但我需要在按下的按钮数字写数字在QlineEdit - 例如在这个计算器:

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import sys 
from PyQt4 import QtGui, QtCore 

class Example(QtGui.QWidget): 
    def __init__(self): 
     super(Example, self).__init__() 
     self.initUI() 

    def initUI(self): 
     numbers = [ '7', '8', '9', 
      '4', '5', '6', 
      '1', '2', '3', 
        '*', '0', '#',] 
     grid = QtGui.QGridLayout() 
     j = 0 
     pos = [(0, 0), (0, 1), (0, 2), 
       (1, 0), (1, 1), (1, 2), 
       (2, 0), (2, 1), (2, 2), 
       (3, 0), (3, 1), (3, 2), 
       ] 
     for i in numbers: 
      button = QtGui.QPushButton(i) 
      grid.addWidget(button, pos[j][0], pos[j][1]) 
      j = j + 1 
     self.setLayout(grid) 
     self.move(300, 150) 
     self.setWindowTitle('Calculator')  
     self.show() 

def main(): 
    app = QtGui.QApplication(sys.argv) 
    ex = Example() 
    sys.exit(app.exec_()) 

if __name__ == '__main__': 
    main() 

回答

0

您需要的按钮连接到一个点击事件,这里是更新后的代码就像那个视频:)

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import sys 
from functools import partial 
from PyQt4 import QtGui, QtCore 

class Example(QtGui.QWidget): 
    def __init__(self): 
     super(Example, self).__init__() 
     self.initUI() 

    def initUI(self): 
     numbers = [ '7', '8', '9', 
      '4', '5', '6', 
      '1', '2', '3', 
        '*', '0', '#',] 
     self.vert_lay = QtGui.QVBoxLayout() 
     self.dig_out = QtGui.QLineEdit() 
     self.vert_lay.addWidget(self.dig_out) 
     grid = QtGui.QGridLayout() 
     j = 0 
     pos = [(0, 0), (0, 1), (0, 2), 
       (1, 0), (1, 1), (1, 2), 
       (2, 0), (2, 1), (2, 2), 
       (3, 0), (3, 1), (3, 2), 
       ] 
     for i in numbers: 
      button = QtGui.QPushButton(i) 
      grid.addWidget(button, pos[j][0], pos[j][1]) 
      j = j + 1 
      button.clicked.connect(partial(self.addNumber,i)) 

     self.vert_lay.addLayout(grid) 
     self.setLayout(self.vert_lay) 

     self.move(300, 150) 
     self.setWindowTitle('Calculator')  
     self.show() 

    def addNumber(self,num): 
     current_txt = self.dig_out.text() 
     self.dig_out.setText("%s%s" % (current_txt,num)) 

def main(): 
    app = QtGui.QApplication(sys.argv) 
    ex = Example() 
    sys.exit(app.exec_()) 

if __name__ == '__main__': 
    main()