How to create toggle switch button in qt designer?

谁都会走 提交于 2020-11-28 02:10:59

问题


I am trying to create toggle button in qt designer. I refer on internet also but i couldn't find how to do that. Can anyone know how to do toggle switch button. I have attached a sample button image.

EDIT

I created a text box below that i want this toggle button. When i try to add it throws me error. How to add the button below the text area? i have attached the code snippet also.

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QPropertyAnimation, QRectF, QSize, Qt, pyqtProperty
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import (
    QAbstractButton,
    QApplication,
    QHBoxLayout,
    QSizePolicy,
    QWidget,
)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
       MainWindow.setObjectName("MainWindow")
       MainWindow.resize(472, 180)
       self.centralwidget = QtWidgets.QWidget(MainWindow)
       self.centralwidget.setObjectName("centralwidget")
       self.url = QtWidgets.QLineEdit(self.centralwidget)
       self.url.setGeometry(QtCore.QRect(30, 20, 411, 31))
       font = QtGui.QFont()
       font.setFamily("MS Shell Dlg 2")
       font.setPointSize(10)
       font.setBold(True)
       font.setWeight(75)
       self.url.setFont(font)
       self.url.setAutoFillBackground(False)
       self.url.setStyleSheet("border-radius:10px;")
       self.url.setAlignment(QtCore.Qt.AlignCenter)
       self.url.setCursorMoveStyle(QtCore.Qt.LogicalMoveStyle)
       self.url.setObjectName("url")
       MainWindow.setCentralWidget(self.centralwidget)
       self.menubar = QtWidgets.QMenuBar(MainWindow)
       self.menubar.setGeometry(QtCore.QRect(0, 0, 472, 21))
       self.menubar.setObjectName("menubar")
       MainWindow.setMenuBar(self.menubar)
       self.statusbar = QtWidgets.QStatusBar(MainWindow)
       self.statusbar.setObjectName("statusbar")
       MainWindow.setStatusBar(self.statusbar)

       self.retranslateUi(MainWindow)
       QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
       _translate = QtCore.QCoreApplication.translate
       MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
       self.url.setPlaceholderText(_translate("MainWindow", "Playlist URL"))

if __name__ == "__main__":
    import sys
    main()
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

回答1:


Qt Designer to set the position and initialize some properties of the widgets in a window, but it does not work to create widgets with custom painted as the switch so you will have to implement with python. Long ago for a project implement a switch so it will show that code:

from PyQt5.QtCore import QObject, QSize, QPointF, QPropertyAnimation, QEasingCurve, pyqtProperty, pyqtSlot, Qt
from PyQt5.QtGui import  QPainter, QPalette, QLinearGradient, QGradient
from PyQt5.QtWidgets import QAbstractButton, QApplication, QWidget, QHBoxLayout, QLabel


class SwitchPrivate(QObject):
    def __init__(self, q, parent=None):
        QObject.__init__(self, parent=parent)
        self.mPointer = q
        self.mPosition = 0.0
        self.mGradient = QLinearGradient()
        self.mGradient.setSpread(QGradient.PadSpread)

        self.animation = QPropertyAnimation(self)
        self.animation.setTargetObject(self)
        self.animation.setPropertyName(b'position')
        self.animation.setStartValue(0.0)
        self.animation.setEndValue(1.0)
        self.animation.setDuration(200)
        self.animation.setEasingCurve(QEasingCurve.InOutExpo)

        self.animation.finished.connect(self.mPointer.update)

    @pyqtProperty(float)
    def position(self):
        return self.mPosition

    @position.setter
    def position(self, value):
        self.mPosition = value
        self.mPointer.update()

    def draw(self, painter):
        r = self.mPointer.rect()
        margin = r.height()/10
        shadow = self.mPointer.palette().color(QPalette.Dark)
        light = self.mPointer.palette().color(QPalette.Light)
        button = self.mPointer.palette().color(QPalette.Button)
        painter.setPen(Qt.NoPen)

        self.mGradient.setColorAt(0, shadow.darker(130))
        self.mGradient.setColorAt(1, light.darker(130))
        self.mGradient.setStart(0, r.height())
        self.mGradient.setFinalStop(0, 0)
        painter.setBrush(self.mGradient)
        painter.drawRoundedRect(r, r.height()/2, r.height()/2)

        self.mGradient.setColorAt(0, shadow.darker(140))
        self.mGradient.setColorAt(1, light.darker(160))
        self.mGradient.setStart(0, 0)
        self.mGradient.setFinalStop(0, r.height())
        painter.setBrush(self.mGradient)
        painter.drawRoundedRect(r.adjusted(margin, margin, -margin, -margin), r.height()/2, r.height()/2)

        self.mGradient.setColorAt(0, button.darker(130))
        self.mGradient.setColorAt(1, button)

        painter.setBrush(self.mGradient)

        x = r.height()/2.0 + self.mPosition*(r.width()-r.height())
        painter.drawEllipse(QPointF(x, r.height()/2), r.height()/2-margin, r.height()/2-margin)

    @pyqtSlot(bool, name='animate')
    def animate(self, checked):
        self.animation.setDirection(QPropertyAnimation.Forward if checked else QPropertyAnimation.Backward)
        self.animation.start()


class Switch(QAbstractButton):
    def __init__(self, parent=None):
        QAbstractButton.__init__(self, parent=parent)
        self.dPtr = SwitchPrivate(self)
        self.setCheckable(True)
        self.clicked.connect(self.dPtr.animate)

    def sizeHint(self):
        return QSize(84, 42)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        self.dPtr.draw(painter)

    def resizeEvent(self, event):
        self.update()


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = Switch()
    w.show()
    sys.exit(app.exec_())

Note: Another possible solution within the Qt world is to use the QML Switch1, 2 component.

Note: In this post I point out how to add custom widgets to a .ui file.




回答2:


A possible solution is to use a stylesheet with a QCheckBox. Just edit the stylesheet for the check box with the following code:

    QCheckBox::indicator:unchecked {
        image: url(switch_off.png);
    }
    QCheckBox::indicator:checked {
        image: url(switch_on.png);
    }

Minimal running example:

from PyQt5 import QtWidgets
import sys

app = QtWidgets.QApplication(sys.argv)
switch = QtWidgets.QCheckBox()
switch.setStyleSheet('''
    QCheckBox::indicator:unchecked {
        image: url(switch_off.png);
    }
    QCheckBox::indicator:checked {
        image: url(switch_on.png);
    }
''')
switch.show()
sys.exit(app.exec_())

Unfortunately, this doesn't always work well if you need some resizing and want the checkbox to adjust its appearance.

The only alternative is to subclass a QPushButton/QAbstractButton (with the checkable() property set to True) and implement the paintEvent on your own, as already suggested by the answer from eyllanesc.



来源:https://stackoverflow.com/questions/62363953/how-to-create-toggle-switch-button-in-qt-designer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!