我有一个按钮可以在QTabWidget中添加选项卡。但是,当我更改按钮的大小时,它不再在角落里了。那么,如何像第一张照片一样将其带到角落呢?

不变大小:



更改大小:



这是我的代码:

from PyQt4 import QtGui, QtCore


class PlaylistTable(QtGui.QWidget):
    def __init__(self):
        super(PlaylistTable, self).__init__()
        self.playlistTable = QtGui.QTableWidget(self)
        self.playlistTable.setFrameShape(QtGui.QFrame.NoFrame)
        self.playlistTable.setFrameShadow(QtGui.QFrame.Sunken)
        self.playlistTable.setLineWidth(0)
        self.playlistTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.playlistTable.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)
        self.playlistTable.setHorizontalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel)
        self.playlistTable.setShowGrid(True)
        self.playlistTable.setGridStyle(QtCore.Qt.SolidLine)
        self.playlistTable.setWordWrap(True)
        self.playlistTable.setCornerButtonEnabled(True)
        self.playlistTable.verticalHeader().setVisible(False)


class CustomTabWidget(QtGui.QTabWidget):
    """Tab Widget that that can have new tabs easily added to it."""

    def __init__(self, parent=None):
        super(CustomTabWidget, self).__init__(parent)
        # QtGui.QTabWidget.__init__(self, parent)

        # Tab Bar
        self.tab = QtGui.QTabBar()
        self.setTabBar(self.tab)

        # Properties
        self.setMovable(True)
        self.setTabsClosable(True)

        self.plusButton = QtGui.QPushButton("+")
        self.plusButton.setFixedSize(QtCore.QSize(22, 22))
        self.setCornerWidget(self.plusButton)

        # Signals
        self.connect(self.plusButton, QtCore.SIGNAL('clicked()'), self.addTab)
        # self.tab.plusClicked.connect(self.addTab)
        self.tab.tabMoved.connect(self.tab.moveTab)
        self.tabCloseRequested.connect(self.removeTab)

    def addTab(self):
        string = QtCore.QString.fromUtf8("Playlist")
        tab = PlaylistTable()
        super(CustomTabWidget, self).addTab(tab, string)


class AppDemo(QtGui.QMainWindow):
    def __init__(self):
        super(AppDemo, self).__init__()
        self.centralwidget = QtGui.QWidget(self)
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setContentsMargins(0, -1, 0, -1)

        self.playlist_manager = CustomTabWidget(self.centralwidget)

        self.horizontalLayout.addWidget(self.playlist_manager)

        self.playlist_manager.addTab()
        self.setCentralWidget(self.centralwidget)

        self.show()
# end class AppDemo


def main():
    import sys
    app = QtGui.QApplication(sys.argv)

    w = AppDemo()
    w.setWindowTitle('AppDemo')
    w.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

最佳答案

我猜是QTabWidget文档中的原因:


  确定小部件的几何形状
  基于小部件的sizeHint()和style()。


如果打印QPushButton的sizeHint(),您将看到宽度永远不会低于特定值。

我发现一种替代方法是使用QToolButton,它可以完成QPushButton的所有工作(甚至更多)。

self.plusButton = QtGui.QToolButton(self)
self.plusButton.setText("+")

10-08 15:41