簡體   English   中英

通過單擊按鈕,選中復選框時,打印在QLineEdit中輸入的一些文本PyQt4

[英]By clicking a button, print some texts entered in QLineEdit when a checkbox is checked PyQt4

通過單擊按鈕,我想打印選中復選框后在QLineEdit中輸入的一些文本。 我的示例代碼如下:

import sys
import PyQt4
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Widget(QWidget):
    def __init__(self, parent= None):
        super(Widget, self).__init__(parent)
        layout = QGridLayout()

        self.setLayout(layout)

        self.checkBox = QCheckBox()
        layout.addWidget(self.checkBox, 0, 0)


        self.le = QLineEdit()
        layout.addWidget(self.le, 0, 1)

        self.btn = QPushButton('Run')
        layout.addWidget(self.btn, 0, 3)


class Func ():
    def __init__(self):
        a = Widget(self)

    def someFunc(self):
        ##print ()


app = QApplication(sys.argv)
widget = Widget()
widget.show()
app.exec_()

如您在上面看到的,我希望“ Widget”類中的按鈕連接到“ Func”類中的“ someFunc”方法。 因此,當在“ self.le”中輸入了一些文本以及選中了“ checkBox”時,我希望“ someFunc”通過單擊按鈕來打印在“ self.le”中輸入的文本。 如果未選中“復選框”,則即使輸入了一些文本,單擊按鈕也不會導致任何事情發生。

如果有人知道如何解決,請讓我知道謝謝!!

您需要將按鈕的單擊信號連接到將要處理的功能。 像這樣: button.clicked.connect(handler_function)

import sys
import PyQt5
from PyQt5.QtWidgets import *

class Func ():
    def __init__(self, widget):
        self.w = widget

    def someFunc(self):
        if self.w.checkBox.isChecked():
            print(self.w.le.text())

class Widget(QWidget):
    def __init__(self, parent= None):
        super(Widget, self).__init__(parent)
        layout = QGridLayout()

        self.setLayout(layout)

        self.checkBox = QCheckBox()
        layout.addWidget(self.checkBox, 0, 0)


        self.le = QLineEdit()
        layout.addWidget(self.le, 0, 1)

        self.btn = QPushButton('Run')
        layout.addWidget(self.btn, 0, 3)

        # connecting to a method in this class
        # self.btn.clicked.connect(self.some_func)

        #connecting to a method in another class
        self.handler_class = Func(self)
        self.btn.clicked.connect(self.handler_class.someFunc)

    def some_func(self):
        if self.checkBox.isChecked():
            print(self.le.text())


app = QApplication(sys.argv)
widget = Widget()
widget.show()
app.exec_()

編輯:簡單地說:在Func類中, self.w包含對小部件的引用,單擊該按鈕時將從該小部件發出信號。

為什么我要引用該小部件? 這樣我就可以訪問小部件的comboboxlineedit 如果沒有訪問它們的方法,我將看不到checkbox是否被選中,或者用戶在textedit鍵入了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM