简体   繁体   中英

PyQt4: How/when to emit custom signal from subclass of QTabWidget?

I have a UI with a QTabWidget whose last tab allows the user to add a new tab, as in Firefox :

插图

But I can't quite get the behaviour that I need. For now, I have used the signal currentChanged(int) , but as its name states, if the user clicks 2 times on that '+' tab, it will emit the signal only the first time. I want my homemade addTab method to be launched every time the '+' tab is clicked, not only when the current tab has been changed.

So I was thinking about creating a subclass of QTableWidget to add a homemade signal, named for example tabClicked . But I can't understand when the signal is emitted. This is what I have so far :

from PyQt4 import QtGui
from PyQt4.QtCore import pyqtSignal

class QTableWidgetClickable(QtGui.QTabWidget):
    tabClicked = pyqtSignal(int)

    def __init__(self, parent=None):
        super(QTableWidgetClickable, self).__init__(parent)

    def tabClicked(self):
        print "tab clicked!"

Should I emit, with something like self.emit(SIGNAL("tabClicked(int)") ? But when? How do I make the computer understand that I want this behaviour only when a tab is clicked? Am I overcomplicating things?

I am very comfortable using signals but it looks like I'm not quite as comfortable creating them :) Please ask for more details if I'm not being clear enough.

Thanks a lot in advance!

I would suggest that you add a QPushButton like this:

class QTableWidgetClickable(QtGui.QTabWidget):
    tabClicked = pyqtSignal(int)

    def __init__(self, parent=None):
        super(QTableWidgetClickable, self).__init__(parent)

        # add qpushbutton
        self.addButton = QtGui.QPushButton()

        # connect a signal
        self.addButton.clicked.connect(self.tabClicked)

    def tabClicked(self):
        print "tab clicked!"

Or you could emit signal like this:

def tabClicked(self):
    print "tab clicked!"
    some_intiger = 0
    self.tabClicked.emit(some_intiger)

And than you should connect this emited signal to some new function in __init__()

def __init__():
    self.tabClicked.connect(self.addTab)

def addTab():
    # this function is executed ever time you emit signal from `self.tabClicked()`
    print "addTab?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM