I want to run the function removeHi(self)
only once in my program, how to accomplish this. Please advise me. My entire code below:
import sys
from PyQt5.QtWidgets import *
from functools import wraps
class TestWidget(QWidget):
gee = ''
def __init__(self):
global gee
gee = 'Hi'
QWidget.__init__(self, windowTitle="A Simple Example for PyQt.")
self.outputArea=QTextBrowser(self)
self.outputArea.append(gee)
self.helloButton=QPushButton("reply", self)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.outputArea)
self.layout().addWidget(self.helloButton)
self.helloButton.clicked.connect(self.removeHi)
self.helloButton.clicked.connect(self.sayHello)
def removeHi(self):
self.outputArea.clear()
def sayHello(self):
yourName, okay=QInputDialog.getText(self, "whats your name?", "name")
if not okay or yourName=="":
self.outputArea.append("hi stranger!")
else:
self.outputArea.append(f"hi,{yourName}")
app=QApplication(sys.argv)
testWidget=TestWidget()
testWidget.show()
sys.exit(app.exec_())
The GUI will show "Hi" when the program runs. I want the "Hi" in QTextBrowser
removed after I push the button reply
, but the program will clear everything in the text browser whenever I clicked the button.
My goal is: only the first Hi
be removed, and the name from function sayHello(self)
will remain whenever I push the reply
button.
CodePudding user response:
The problem resides in the logic of your program: you should check whether the text must be cleared or not, using a default value that would be changed whenever the dialog changes the output:
class TestWidget(QWidget):
clearHi = True
def __init__(self):
QWidget.__init__(self, windowTitle="A Simple Example for PyQt.")
self.outputArea = QTextBrowser()
self.outputArea.append('Hi')
self.helloButton = QPushButton("reply")
layout = QVBoxLayout(self)
layout.addWidget(self.outputArea)
layout.addWidget(self.helloButton)
self.helloButton.clicked.connect(self.removeHi)
self.helloButton.clicked.connect(self.sayHello)
def removeHi(self):
if self.clearHi:
self.outputArea.clear()
def sayHello(self):
yourName, okay = QInputDialog.getText(
self, "whats your name?", "name")
if not okay:
return
self.clearHi = False
if not yourName:
self.outputArea.append("hi stranger!")
else:
self.outputArea.append(f"hi, {yourName}")
Note: do not use globals.